[英]Javascript: Why is my code alerting to nothing?
I've written the following: 我写了以下内容:
var pages=["[www.facebook.com] Facebook is cool. ","[www.bbc.co.uk] British broadcasting corporation. "];
function findScoreC2(s){
var scores=[];
var percentageScores=[];
var contentsArray=[];
s=s.toLowerCase();
for(i=0;i<pages.length; i++){
contentsArray=pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "));
var lowerCaseContents=(pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "))).toLowerCase();
scores[i] =(lowerCaseContents.split(s)).length-1
};
percentageScores=(scores[i] / contentsArray[i].length) * 100;
var finalArray=[];
for(i=0;i<percentageScores.length;i++){
finalArray.push("{score:"+percentageScores[i]+",index:"+i+"}")
};
alert(finalArray);
}
findScoreC2("facebook");
however, alert(finalArray)
alerts to nothing (ie an alert box comes up but it says nothing) when it should alert "{score:33,index:0},{score:0,index:1}"
. 但是,当alert(finalArray)
应该警告"{score:33,index:0},{score:0,index:1}"
时,什么也不会警告(即出现警告框,但什么也没说)。
Could anyone enlighten me as to why this might be? 有人能启发我为什么会这样吗?
Thanks very much 非常感谢
You set percentageScores
to a number. 您将percentageScores
设置为一个数字。 You then try to iterate up to its length
property, which gives you undefined
when you do percentageScores.length
, so the for loop never iterates. 然后,您尝试迭代到它的length
属性,使您undefined
当你这样做percentageScores.length
,所以for循环迭代永远。 You then alert with an empty array, whose toString
produces the empty string. 然后,您使用一个空数组发出警报,该数组的toString
生成空字符串。
You probably want this: 您可能想要这样:
for(i=0;i<pages.length; i++){
contentsArray=pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "));
var lowerCaseContents=(pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "))).toLowerCase();
scores[i] =(lowerCaseContents.split(s)).length-1
percentageScores[i]=(scores[i] / contentsArray[i].length) * 100;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.