+ 6

I need JavaScript chalenge explanation

Hey guys, can anyone explain this JS function in plain english? It is one if the chalenges on SoloLearn... 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); // output is 3

1st Jan 2018, 2:09 PM
Dusko Stamenic
Dusko Stamenic - avatar
3 odpowiedzi
+ 16
The function findl was called by passing in 2 parameters: array [3, 2, 1, 4, 5] as v number 4 as t Inside the function the for loop iterates the array and try to determine whether the current entry match with the number, if it's yes, return the index back to the caller. If the function never return in the for loop that means there's no matching number in the array and hence it will return -1. In short, the function's objective is to get the index of the corresponding number if it exists in the array, otherwise -1. ➕ Additional notes: ✅ You may recall that array index count from 0. ✅ There's a built in function which achieve the same goal, namely indexOf. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
1st Jan 2018, 2:33 PM
Zephyr Koo
Zephyr Koo - avatar
+ 3
var I=0;I<v.length and the v.length is 5 if (v[I]==T) return I the value of t is 4 so if v[I]==4 return I.in the array the fourth element ==4 so v[3]==4 then the function returns 3
1st Jan 2018, 2:24 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 1
Both of you guys, clarified it realy good. Now I understand how that function works! Thank you!
1st Jan 2018, 7:42 PM
Dusko Stamenic
Dusko Stamenic - avatar