Wednesday, December 26, 2018
How do I check if an array includes a value in JavaScript?
Answer
Answer
What is the most concise and efficient way to find out if a JavaScript array contains a value?
This is the only way I know to do it:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
Is there a better and more concise way to accomplish this?
This is very closely related to question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf
.
Answer
Current browsers have Array#includes
, which does exactly that, is widely supported, and has a polyfill for older browsers.
> ['joe', 'jane', 'mary'].includes('jane');
true
You can also use Array#indexOf
, which is less direct, but doesn't require Polyfills for out of date browsers.
jQuery offers $.inArray
, which is functionally equivalent to Array#indexOf
.
underscore.js, a JavaScript utility library, offers _.contains(list, value)
, alias _.include(list, value)
, both of which use indexOf internally if passed a JavaScript array.
Some other frameworks offer similar methods:
Notice that some frameworks implement this as a function, while others add the function to the array prototype.
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
I need to do the following: My current address looks like: https://www.domain.com I want to redirect with htaccess: www.domain.com TO https:...
-
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programm...
-
using namespace std; So far in my computer science courses, this is all we have been told to do. Not only that, but it's all tha...
No comments:
Post a Comment