Tips on how to use indexOf in JavaScript _ basic knowledge

Source: Internet
Author: User
The indexOf method is used to return the index of the target string (which can be viewed as an array of characters) or the items equal to x in the Array Based on the given parameter x. This method is quite useful. Many programming languages have corresponding implementations, and javascript is no exception. However, when I run the following code in ie:

The Code is as follows:


Var arr = [1, 2, 3];
Alert (arr. indexOf (1 ));


"The object does not support this attribute and method ". However, it works well in chrome and ff. I went to ask google, and found that the Array indexOf method in js was implemented only in js1.6. ie7 and 8 were implemented only in js1.3 and chrome was js1.7, ff is js1.8. (Ie is still half-beat ). But I had to expand ie:

The Code is as follows:


Array. prototype. _ indexOf = function (n ){
If ("indexOf" in this ){
Return this ["indexOf"] (n );
}
For (var I = 0; I If (n = this [I]) {
Return I;
}
}
Return-1;
};


Use:

The Code is as follows:


Var arr = ["1", "2", "3"];
Alert (arr. _ indexOf ("2 "));


Here we have extended the Array prototype and added the "_" character to the extension method name. I think this is a good habit, you need to mark your extensions when you scale your prototype.
In the _ indexOf method, we first determine whether the current Array has implemented the "indexOf" method. If yes, directly call the system method; 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.