如果我这样做:
for (var i in obj) { if (obj.hasOwnProperty(i)) console.log("Has property: " + i); else console.log("Doesn't have property: " + i); }
obj.hasOwnProperty(i)会不会返回false?如果是的话,何时?
解决方法
在循环中使用hasOwnProperty的想法是在循环继承属性时解析为false.这避免了道格拉斯·克罗克福德所说的“深挖”.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty的示例:
var buz = { fog: 'stack' }; for (var name in buz) { if (buz.hasOwnProperty(name)) { alert("this is fog (" + name + ") for sure. Value: " + buz[name]); } else { alert(name); // toString or something else } }