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.
Subscribe to:
Post Comments (Atom)
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 ...
-
I would like to split a String by comma ',' and remove whitespace from the beginning and end of each split. For example, if I have ...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
No comments:
Post a Comment