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.