The result will be false
as Ben is not present in the array.
if (nameArray.indexOf(name) > -1)
To avoid repetitive typing, you can create a contains()
method for the Array
class.
// Static method
if (Array.contains === undefined) {
Array.contains = function(arr, val) {
return arr.indexOf(val) > -1;
}
}
// Instance method
if (Array.prototype.contains === undefined) {
Array.prototype.contains = function(val) {
return this.indexOf(val) > -1;
}
}
var nameArray = ["Bill", "Barry", "Zack", "Will"];
var name = "Ben";
Array.contains(nameArray, name); // false
nameArray.contains(name); // false
Another option is to use Array.prototype.some
.
if (Array.prototype.contains === undefined) {
Array.prototype.contains = function(val) {
return this.some(function(item) {
return item === name;
});
}
}
An alternative approach is to polyfill Array.prototype.includes()
, a forthcoming method in ECMAScript 7.
Polyfill
if (![].includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
Usage
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true