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

时间:2021-09-29 21:07:21

I'm trying to figure out why the values in my chart are not coming out correctly. When I log the values of learningLanguages[j].count++ as it is looping they are accurate. However, when I log n in the map function in the chart $.map(nativeLanguages, function(n) {...}), the counts are all incorrect (and seemingly arbitrary)

我想弄清楚为什么我的图表中的值没有正确出现。当我记录learningLanguages [j] .count ++的值时,因为它是循环的,所以它们是准确的。但是,当我在图表$ .map(nativeLanguages,function(n){...})中的map函数中记录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 个解决方案

#1


7  

Part of your problem stems from pushing the same object into the 2 different arrays here:

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

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

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

This does not copy currentLanguage into each, it pushes references of the same object into each.

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

Then whatever you do to that object reference in one will be reflected in the other

然后,无论你对该对象做什么,一个中的引用都会反映在另一个中

Try making 2 separate objects

尝试制作2个独立的对象

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

the use of global variables will also get you into trouble...don't do it!

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

#2


1  

learningLanguages = []
nativeLanguages = []

These two variables look like they are not defined in an above scope - thus the second XHR call does not know about these variables.

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

Second piece of the answer is reference to the same object instance, with the same "count" attribute touched twice.

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

I'd suggest two options are here:

我建议有两种选择:

  • use new Language(...) for each of these two arrays separately
  • 分别为这两个数组中的每一个使用新的语言(...)

  • or have a separate counter for each type of native/learning counts.
  • 或者为每种类型的原生/学习计数设置单独的计数器。

#1


7  

Part of your problem stems from pushing the same object into the 2 different arrays here:

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

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

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

This does not copy currentLanguage into each, it pushes references of the same object into each.

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

Then whatever you do to that object reference in one will be reflected in the other

然后,无论你对该对象做什么,一个中的引用都会反映在另一个中

Try making 2 separate objects

尝试制作2个独立的对象

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

the use of global variables will also get you into trouble...don't do it!

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

#2


1  

learningLanguages = []
nativeLanguages = []

These two variables look like they are not defined in an above scope - thus the second XHR call does not know about these variables.

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

Second piece of the answer is reference to the same object instance, with the same "count" attribute touched twice.

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

I'd suggest two options are here:

我建议有两种选择:

  • use new Language(...) for each of these two arrays separately
  • 分别为这两个数组中的每一个使用新的语言(...)

  • or have a separate counter for each type of native/learning counts.
  • 或者为每种类型的原生/学习计数设置单独的计数器。