This method is quite useful, many programming languages have a corresponding implementation, JavaScript is no exception, however, when I run the following code in IE:
Copy Code code as follows:
var arr = [1,2,3];
Alert (Arr.indexof (1));
It is prompted that "the object does not support this property and method." And in Chrome,ff down to run well. So to ask Google great God, found that the original JS array in the IndexOf method in js1.6 version only to give the implementation, ie7,8 only to achieve the js1.3 version, Chrome for js1.7 version, FF for js1.8 version. (ie is still half a slow shot). Helpless, had to expand for IE:
Copy Code code as follows:
Array.prototype._indexof = function (n) {
if ("IndexOf" in this) {
return this["IndexOf"] (n);
}
for (Var i=0;i<this.length;i++) {
if (N===this[i]) {
return i;
}
}
return-1;
};
Use the following:
Copy Code code as follows:
var arr = ["1", "2", "3"];
Alert (Arr._indexof ("2"));
Here we have extended the array prototype, and I've added the "_" character to the name of the extension method, which I think is a good habit when you need to tag your extensions as you extend the prototype.
In the _indexof method, we first determine whether the current array implements the "IndexOf" method, and if so, call the system directly, otherwise traverse.