hasOwnProperty(name) 方法会返回一个布尔值,判断对象自身属性中是否含有指定的属性(含有返回 true,否则返回 false。记住,这里是属性啊,不是值!!因为对于数组来说,属性是索引),这里只检查自身而不去查找原型链上的属性(注:对 name 为 hasOwnProperty 时也不起作用);而 in 运算符会去查找原型链。
// 用法:obj.hasOwnProperty('prop');
obj = new Object();
obj.say = "hello";
obj.hasOwnProperty('say'); // true
obj.hasOwnProperty("toString"); // false toSting属于原型链上的属性
// in 用法: prop in obj
var trees = new Array('name', 'value');
console.log(0 in trees); // 返回 true 0表示第一个元素的索引
console.log('name' in trees) // 返回false (必须使用索引号,而不是数组元素的值)
console.log('length' in trees); // 返回true,因为 length 是 trees 原型链中的属性