i need to determine if a value exists in an array using javascript.
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"));
Please suggest what to do
Solution
arrValues.indexOf('Sam') > -1
IE 8 and below do not have the Array.prototype.indexOf
method. For these versions of IE use:
if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(needle) {
for(var i = 0; i < this.length; i++) {
if(this[i] === needle) {
return i;
}
}
return -1;
};
}
Edit after a long time: It’s best not to patch the prototype
of native primitives in JavaScript. A better way:
var indexOf = function(needle) {
if(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++) {
if(this[i] === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle);
};
You can use it like this:
var myArray = [0,1,2],
needle = 1,
index = indexOf.call(myArray, needle); // 1
The function will detect the presence of a native indexOf
method, once, then overwrite itself with either the native function or the shim.
Related
The post JavaScript Determine Whether an Array Contains a Value appeared first on Solved.