简体   繁体   English

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

[英]Can't figure out why the values in my objects are changing

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. 当我记录learningLanguages[j].count++的值时,因为它是循环的,所以它们是准确的。 However, when I log n in the map function in the chart $.map(nativeLanguages, function(n) {...}) , the counts are all incorrect (and seemingly arbitrary) 但是,当我在图表$.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
                }
            });
        })
    });
}   

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! 使用全局变量也会让你陷入困境......不要这样做!

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 分别为这两个数组中的每一个使用new Language(...)
  • or have a separate counter for each type of native/learning counts. 或者为每种类型的native/learning计数设置单独的计数器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的innerHTML命令没有更改任何内容,我不知道为什么 - My innerHTML command isn't changing anything and i can't figure out why Javascript&#39;this&#39;值改变了,但无法弄清楚原因 - Javascript 'this' value changing, but can't figure out why 无法弄清楚为什么我的math.random在for循环中返回错误的值 - Can't figure out why my math.random is returning the incorrect values whilst in a for loop 我的简单路由无法正常工作,我不知道为什么 - My simple routing is not working and I can't figure out why 无法弄清楚为什么我的网站加载如此缓慢 - Can't figure out why my site loads so slow 无法弄清楚为什么我的Instagram照片没有出现在Instafeed? - Can't figure out why my the Instagram pictures are not appearing with Instafeed? 无法弄清楚为什么我的提交按钮不会提交 - Can't Figure out why my submit button wont submit 无法弄清楚为什么我的标题的其余部分不会显示 - Can't figure out why the rest of my header will not show 我不知道为什么我的JavaScript无法正常工作…我正在将值动态传递给标签 - I can't figure out why my javascript isn't working… I'm dynamically passing values to a tag 无法弄清楚我在这个加密 web 应用程序中做错了什么。 为什么要更改错误的字母? - Can't figure out what I did wrong in this encryption web app. Why it is changing the wrong letters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM