开发者

Javascript: Why is my code alerting to nothing?

I've开发者_StackOverflow中文版 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


You set percentageScores to a number. 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. You then alert with an empty array, whose toString produces the empty string.

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;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜