JavaScript for…in vs for

前端 未结 22 1618
悲哀的现实
悲哀的现实 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

    Using forEach to skip the prototype chain

    Just a quick addendum to @nailer's answer above, using forEach with Object.keys means you can avoid iterating over the prototype chain without having to use hasOwnProperty.

    var Base = function () {
        this.coming = "hey";
    };
    
    var Sub = function () {
        this.leaving = "bye";
    };
    
    Sub.prototype = new Base();
    var tst = new Sub();
    
    for (var i in tst) {
        console.log(tst.hasOwnProperty(i) + i + tst[i]);
    }
    
    Object.keys(tst).forEach(function (val) {
        console.log(val + tst[val]);
    });
    

提交回复
热议问题