Home > Web Front-end > JS Tutorial > JavaScript advanced series - for in loop

JavaScript advanced series - for in loop

黄舟
Release: 2017-02-08 09:31:14
Original
1148 people have browsed it

Use hasOwnProperty to filter

Summary

Like the in operator, the for in loop also traverses all properties on the prototype chain when looking for object properties.

// 修改 Object.prototype
Object.prototype.bar = 1;

var foo = {moo: 2};
for(var i in foo) {
    console.log(i); // 输出两个属性:bar 和 moo
}
Copy after login

Since it is impossible to change the behavior of for in itself, it is necessary to filter out those properties that do not want to appear in the loop body. This can be done through the hasOwnProperty function on the Object.prototype prototype.

Note: The for in loop will not traverse properties whose enumerable is set to false; such as the length property of an array.

Use hasOwnProperty to filter

// foo 变量是上例中的
for(var i in foo) {
    if (foo.hasOwnProperty(i)) {
        console.log(i);
    }
}
Copy after login

This version of the code is the only correct way to write it. Since we used hasOwnProperty, only moo is output this time. If hasOwnProperty is not used, this code may break when native object prototypes (such as Object.prototype) are extended.

A widely used class library Prototype extends native JavaScript objects. Therefore, when this class library is included in the page, for in loops that do not use hasOwnProperty filtering will inevitably cause problems.


Note: Since for in always traverses the entire prototype chain, performance will be affected if the inheritance level of an object is too deep.

Summary

It is recommended to always use hasOwnProperty, do not make any assumptions about the environment in which the code runs, and do not assume whether the native object has been extended.

The above is the content of the JavaScript advanced series - for in loop. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template