JavaScript for…in vs for

前端 未结 22 1471
悲哀的现实
悲哀的现实 2020-11-22 07:15

Do you think there is a big difference in for...in and for loops? What kind of \"for\" do you prefer to use and why?

Let\'s say we have an array of associative array

22条回答
  •  不要未来只要你来
    2020-11-22 07:22

    Douglas Crockford recommends in JavaScript: The Good Parts (page 24) to avoid using the for in statement.

    If you use for in to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.

    Everything but the properties can be filtered out with .hasOwnProperty. This code sample does what you probably wanted originally:

    for (var name in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, name)) {
            // DO STUFF
        }
    }
    

提交回复
热议问题