在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]);
第一个log语句正确反映了函数中所做的更改(即,sendimentValues [0] .num为2)。第二条日志语句没有。
-控制台中第一条语句的输出扩展为将sentimentValues [0] .num设为2-
控制台中第二条语句的输出将sendimentValues [0] .num设为0 ...
控制台输出的屏幕快照可以在此处查看:http : //lmc.gatech.edu/~epramer3/consoleOutput
这是怎么回事?
当然,如果您粘贴更多代码,这将有所帮助,但是首先尝试更改变量名“ values”。
编辑:我检查了您的代码和屏幕截图,甚至尝试了您的代码,输出结果如预期的那样。看来您使用的是Google Chrome浏览器,是否尝试过一些简单的步骤,例如重新启动浏览器或完全尝试使用其他浏览器?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句