views:

75

answers:

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

+1  A: 

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;
};
Claudiu
Thanks for your reply. I've just given that a try as I realised at roughly the same time you wrote back that I the percentageScores line was outside the for-loop, so i changed the code to include it, and in the for-loop at the end, changed it to iterate up to scores.length (rather than percentage scores). Now, it alerts to "{score:undefined, index:0},{score:undefined, index:1}" but I can't see what the problem is now
Deacon
did you add the [i] to the percentageScores when indexing into it?
Claudiu
I didn't, but having just read your reply and done so, it works! well almost. now i'm getting "{score:100,index:0}" which would seem to indicate that it thinks the value of contentsArray[0] is 1, when it's actually 3 ("Facebook is cool.")?Thanks very much for all your help, I appreciate it.
Deacon