Friday, February 22, 2019

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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; 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...