A summary of the usage and problems of indexof in JavaScript-basic knowledge

Source: Internet
Author: User
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.