Chelsea
Chelsea

Reputation: 335

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

Upvotes: 2

Views: 1162

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

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();

Upvotes: 1

Aplet123
Aplet123

Reputation: 35502

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.

Upvotes: 1

Related Questions