【发布时间】: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