Home >Web Front-end >JS Tutorial >Problems and solutions caused by extending Array.prototype.indexOf for JS_Basic knowledge
Array does not have an indexOf method, so it is troublesome to find the index of an element in an array. For the convenience of calling, Array.prototype.indexOf() is extended through the prototype prototype, which makes it more convenient to use. But there was a problem with this custom indexOf when traversing the array.
Directly when using
After the expansion, it is very comfortable and convenient to use, creating a harmonious scene...
But one time when traversing array elements, a for..in.. loop was used, which caused other problems and broke the harmonious atmosphere.
I originally wanted to output the names of these four people, but what was output?
The output is actually:
In addition to typing out the name, it also outputs its own extended method indexOf. But the crazy thing is that Firefox is "normal" and only has the names of four people. Why is this?
Output indexOf, which can be expanded by itself, which is understandable. After all, for..in traverses all user-defined attributes of an object or all elements of an array.
So why not firefox?
I found out later after checking the information,
Array already supports Array.indexOf() in javascript version 1.6, and the firefox I use is version 3.5, which already supports javascript 1.8. IndexOf is an inherent method of Array itself.
As for IE, even though I am using IE8, it only supports version 1.3 of JavaScript.
So IE8 considers indexOf to be a "user-defined attribute", while Firefox considers it to be an inherent attribute supported by itself natively.
Is this really the case?
Do an experiment, rename indexOf to myIndexOf, and try again. As a result, both IE and firefox output myIndexOf, which proves that the previous point is correct.
Then here comes another problem. I have extended indexOf for a long time. Now many project codes are already using this method, but now I have to use for..in to output the elements of the array itself. I don’t want to extend it myself. What should I do if I get to Russia?
Fortunately, javascript provides the hasOwnProperty method.
Look at its description:
Looking at the description, it’s what we want.
Just make a judgment in for...in.. and it's OK
In addition, here is an example of how to use hasOwnProperty, sourced from the Internet:
查看浏览器支持javascript到哪个版本: