Wednesday, 24 May 2017

javascript - Determine whether an array contains a value





I need to determine if a value exists in an array.



I am using the following function:



Array.prototype.contains = function(obj) {
var i = this.length;

while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}


The above function always returns false.




The array values and the function call is as below:



arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));

Answer



var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;

var indexOf;

if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;

for(i = 0; i < this.length; i++) {
var item = this[i];


if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}

return index;
};
}


return indexOf.call(this, needle) > -1;
};


You can use it like this:



var myArray = [0,1,2],
needle = 1,
index = contains.call(myArray, needle); // true



CodePen validation/usage


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...