很抱歉,这可能是一个愚蠢的问题,但我想知道为什么我经常在某些for / foreach循环中看到测试等。
for (var item in data) {
if (data.hasOwnProperty(item)) {
由于项目确实属于数据(它的一个元素),因此使用hasOwnProperty()方法进行测试的效用是什么?
答案 0 :(得分:1)
清除对象原型(或其原型的原型等)的属性。
示例:
// A prototype object
var p = {
prop1: "proto prop"
};
// Create an object using that as its prototype
var o = Object.create(p);
// Give it a property
o.prop2 = "obj prop";
var key;
snippet.log("All of o's enumerable properties:");
for (name in o) {
snippet.log(name); // We'll see prop2 and prop1
}
snippet.log("Only o's *own* enumerable properties:");
for (name in o) {
if (o.hasOwnProperty(name)) {
snippet.log(name); // We'll see prop2, and *not* prop1
}
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>