无法弄清楚为什么我的对象中的值正在发生变化

时间:2016-09-30 20:05:37

标签: javascript jquery chart.js

我正在试图弄清楚为什么我的图表中的值没有正确显示出来。当我记录learningLanguages[j].count++的值时,它是循环的,它们是准确的。但是,当我在图表n中的地图函数中记录$.map(nativeLanguages, function(n) {...})时,计数都是不正确的(并且看似任意)

var getLanguages = $.get('/languages.json', function(languages){
        // top level language arrays
        learningLanguages = []
        nativeLanguages = []

        // object constructor that correctly formats the language objects
        function Language(lang) {
            this.language = lang;
            this.count = 0;
        }

        // Loop through the languages, create an object for each, push to top level language arrays
        for(i = 0; i < languages.length; i++) {
            currentLanguage = new Language(languages[i].language)

            learningLanguages.push(currentLanguage)
            nativeLanguages.push(currentLanguage)
        }
     });

    // once the languages call is complete find signed-in user's info
    getLanguages.done(function() {
        $.get('/users.json', function(response) {
            // console.log(response)
            // adds the total number of users to the DOM
            var numberOfUsers = response.length
            $('#userCount').append('<h1>Total Users: ' + numberOfUsers + '</h1>')
            // find the number of approved users
            // var numberApproved = 0
            // for (i = 0; i < response.length; i++) {
            //     if (response[i].approved === true) {
            //         numberApproved++
            //     }
            // }
            // Add the number of approved users to the DOM
            // $('#userCount').append('<h1>Total Approved Users: ' + numberApproved + '</h1>')


            // search for the language in the array and increase the count for that language
            for (i = 0; i < response.length; i++) {
                var userLearningLanguage = response[i].learning_language

                for (j = 0; j < learningLanguages.length; j++) {
                    if (learningLanguages[j].language === userLearningLanguage) {
                        learningLanguages[j].count++
                    }
                }
            }
            // search for the language in the array and increase the count for that language
            for (i = 0; i < response.length; i++) {
                var userNativeLanguage = response[i].native_language
                for (j = 0; j < nativeLanguages.length; j++) {
                    if (nativeLanguages[j].language === userNativeLanguage) {
                        nativeLanguages[j].count++
                    }
                }
            }

            var ctx = $("#languageComparisonChart");
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: 
                        $.map(learningLanguages, function(n) {
                            return n.language
                        }),
                    datasets: [{
                        label: '# of Learners',
                        data:  $.map(learningLanguages, function(n) {
                                return n.count
                            }),
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        borderColor: 'rgba(255,99,132,1)',
                        borderWidth: 1
                    },
                    {
                        label: '# of Native Speakers',
                        data:  $.map(nativeLanguages, function(n) {
                            console.log(n)
                                return n.count
                            }),
                        backgroundColor: 'rgba(54, 162, 235, 0.2)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero:true
                            }
                        }]
                    },
                    responsive: false,
                    maintainAspectRatio: true
                }
            });
        })
    });
}   

2 个答案:

答案 0 :(得分:7)

你的部分问题源于将同一个对象推入2个不同的数组:

    for(i = 0; i < languages.length; i++) {
        currentLanguage = new Language(languages[i].language)

        learningLanguages.push(currentLanguage)
        nativeLanguages.push(currentLanguage)
   }

这不会将currentLanguage复制到每个中,它会将同一个对象的引用推送到每个中。

然后,无论你对该对象做什么,一个中的参考都将反映在另一个

尝试制作2个单独的对象

    for(i = 0; i < languages.length; i++) { 
        learningLanguages.push(new Language(languages[i].language))
        nativeLanguages.push(new Language(languages[i].language))
   }

使用全局变量也会让你陷入困境......不要这样做!

答案 1 :(得分:1)

learningLanguages = []
nativeLanguages = []

这两个变量看起来没有在上面的范围中定义 - 因此第二个XHR调用不知道这些变量。

答案的第二部分是对同一个对象实例的引用,同一个“count”属性被触摸了两次。

我建议有两种选择:

  • 分别对这两个数组中的每一个使用new Language(...)
  • 或为每种native/learning计数设置单独的计数器。