Thursday, September 12, 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)
hard drive - Leaving bad sectors in unformatted partition?
Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...
-
My webapp have javascript errors in ios safari private browsing: JavaScript:error undefined QUOTA_EXCEEDED_ERR:DOM Exception 22:An...
-
I would like to use the jquery autocomplete function on a field of a form collection. For example, I have a form collection that got those f...
-
I needed to resize my Boot Camp partition so I used Gparted to move and resize it. This seemed to work, except that now I can't boot int...
No comments:
Post a Comment