Back
Below is the code I’ve:
function inArray(needle,haystack){ var count=haystack.length; for(var i=0;i<count;i++) { if(haystack[i]===needle){return true;} } return false;}
function inArray(needle,haystack)
{
var count=haystack.length;
for(var i=0;i<count;i++)
if(haystack[i]===needle){return true;}
}
return false;
Can anyone tell me if there is a better way to do it?
Use ECMAScript 2016 which has an includes() method for arrays which solves the problem:
[1, 2, 3].includes(2); // true[1, 2, 3].includes(4); // false[1, 2, 3].includes(1, 2); // false (second parameter is the index position in this array
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(1, 2); // false (second parameter is the index position in this array
Interested in Java? Check out this Java tutorial by Intellipaat.
31k questions
32.8k answers
501 comments
693 users