+ 2
Could someone explain me how this code works line to line? Thanks.
function findl(v,t){ for(var i=0;i<v.length;++i){ if (v[i]==t){return i;} } return -1; } var a=findl([3,2,1,4,5],4); alert(a);
3 Answers
+ 5
Rastislav Romanec
Inside the loop declaration prototype,
The initial value of i is 0, the condition to check is i < 5 (5 is the length of array v, passed argument to parameter v). The loop increments by 1 on each iteration.
Inside the loop body,
The if statement checks whether the element in the array v at index i is equal to parameter t (which is 4). The element at 3th index (when i becomes 3) is 4, and it has the same value as variable t. Therefore, 3 gets printed.
+ 4
Is it "v.length" instead of "length"?
+ 4
yes, it is.