Thursday 12 September 2019

javascript - Check if an element is present in an array

Answer


Answer






The function I am using now to check this is the following:



function inArray(needle,haystack)
{
var count=haystack.length;
for(var i=0;i {
if(haystack[i]===needle){return true;}
}
return false;

}


It works. What I'm looking for is whether there is a better way of doing this.


Answer



ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the problem, and so is now the preferred method.



[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 at which to begin searching)



As of JULY 2018, this has been implemented in almost all major browsers, if you need to support IE a polyfill is available.



Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...