Thursday 26 October 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


href="http://codepen.io/anon/pen/mVRNaJ" rel="noreferrer">CodePen
validation/usage


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...