简体   繁体   中英

Simple Javascript for loop stops after first iteration

I've read a bunch of other posts that have had similar issues and still can't figure out why this one is being weird. I tried doing try/catch and no errors were reported. The arrays are actually 100+, but narrowing it down for the example. It works when searching for the first item in the array, but all after that it fails after one iteration attempt. I printed out the array length and it is seeing that the array is over 100 in length.

Edit: I should note that this is the only place a var k is used.

function main(){
  var list = [["feature 123", 5.0], ["feature 234", 38.0], ["feature 345", 38.0]];
  var search = "feature 234";
  var a = getIndexx(list, search);
}

function getIndexx(array, str) {
   for(var k=0; k < array.length; k++) {
     if(array[k][0] === str) {
       return k;
     } else {
       return -1
     }
  }
}

You return -1 inside the for loop, which means if it finds the match on the first index it'll return 0 otherwise it'll immediately return -1 . You want to move the return -1 so it's after the for loop, so if it finds no matches it returns -1.

You do not want an else condition. You only want to return the found index if the condition is valid.

If you did not find a matching value, while looping, then you return -1 .

 function main() { var list = [ ["feature 123", 5.0], ["feature 234", 38.0], ["feature 345", 38.0] ]; var search = "feature 234"; var a = getIndexx(list, search); console.log(a); // 1 } function getIndexx(array, str) { for (var k = 0; k < array.length; k++) { if (array[k][0] === str) { return k; } } return -1; // Should be the default condition } main();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM