【问题标题】:why is my javascript function not applying changes to my global variables?为什么我的 javascript 函数没有对我的全局变量应用更改?
【发布时间】:2014-11-27 12:07:42
【问题描述】:

在javascript中,我将全局变量“sentimentValues”实例化如下:

var sentimentValues = [
    {txt: "good", num: 0},
    {txt: "bad", num: 0},
    {txt: "neutral", num: 0}
    ];

我后来有一个函数,其中全局变量“sentimentValues”被操纵。 函数如下,其中 data 是从 csv 文件创建的数组,每个 d 是 csv 文件中的一个条目。

data.forEach(function(d){
            var strArray = d.message.split(" ");

            d.sentiment = calculateSentiment(strArray);
            if(d.sentiment == "good")
                sentimentValues[0].num += 1;
            else if(d.sentiment == "bad")
                sentimentValues[1].num += 1;
            else
                sentimentValues[2].num += 1;    
        })

其中“calculateSentiment”函数如下:

    function calculateSentiment(wordArray)
    {
                var goodCount = 0;
                var badCount = 0;
                for(var i = 0; i<wordArray.length; i++)
                {
                    for(var index = 0; index<happyWords.length; index++)
                    {
                        if(happyWords[index] == wordArray[i])
                        {
                            goodCount++;
                        }
                    }

                    for(var index = 0; index<sadWords.length; index++)
                    {
                        if(sadWords[index] ==wordArray[i])
                            badCount++;
                    }
                }
                if(goodCount > badCount)
                    return "good";
                else if(badCount > goodCount)
                {
                    return "bad";
                }
                else
                    return "neutral";
    }

和happyWords、sadWords定义为:

    var sadWords;
    var happyWords;

    $.get('happyWords.txt',function(data){
        happyWords = data.split('\n');
    });

    $.get('sadWords.txt',function(data){
        sadWords = data.split('\n');
    });

函数调用后,我调用了这两行:

console.log(sentimentValues);
console.log(sentimentValues[0]);

第一个日志语句正确反映了函数中所做的更改(即,sentimentValues[0].num 为 2)。第二个日志语句没有。

-第一条语句在控制台中的输出扩展为显示sentimentValues[0].num 为2
- 第二条语句的控制台输出显示sentimentValues[0].num 为0...

可以在此处查看控制台输出的屏幕截图:http://lmc.gatech.edu/~epramer3/consoleOutput

这里发生了什么?

【问题讨论】:

  • 能否请您粘贴整个代码,包括操作values数组的函数?
  • 完成。我发布了一个指向控制台屏幕截图的链接(因为我没有足够的声誉来包含图像)

标签: javascript arrays function variables global


【解决方案1】:

当然,如果您粘贴更多代码会有所帮助,但首先尝试更改变量名称“values”。

编辑: 我检查了您的代码和屏幕截图,甚至尝试了您的代码,并且输出符合预期。 您似乎正在使用 Google Chrome,您是否尝试了一些简单的步骤,例如重新启动浏览器或完全尝试其他浏览器?

【讨论】:

  • 这不是一个答案,只是一个评论!
  • @LShetty 他没有足够的声誉来发表评论
  • 而且我没有足够的声誉来发布控制台的图片 :( 描述比展示更难
  • @asakka,呃,我觉得很傻。 Firefox 工作 -_- 有时你会忘记一些小事......
猜你喜欢
  • 2019-04-01
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 2015-03-03
  • 2022-01-19
  • 2014-08-23
相关资源
最近更新 更多