Javascript:为什么我的代码没有任何警报?
我编写了以下内容:
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");
但是,当它应该发出警报 "{score:33,index: 0},{得分:0,索引:1}"
。
谁能告诉我为什么会这样?
非常感谢
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}"
.
Could anyone enlighten me as to why this might be?
Thanks very much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将
percentageScores
设置为一个数字。然后,您尝试迭代其length
属性,当您执行percentageScores.length
时,该属性会给出undefined
,因此 for 循环永远不会迭代。然后,您使用一个空数组发出警报,其toString
会生成空字符串。你可能想要这个:
You set
percentageScores
to a number. You then try to iterate up to itslength
property, which gives youundefined
when you dopercentageScores.length
, so the for loop never iterates. You then alert with an empty array, whosetoString
produces the empty string.You probably want this: