This method is quite useful. Programming Language And Javascript is no exception. However, when I run the following Code Time:
Copy code 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:Copy codeThe Code is 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:Copy codeThe 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.