javascript – Object.keys(anObject)是否返回anObject的原型?

前端之家收集整理的这篇文章主要介绍了javascript – Object.keys(anObject)是否返回anObject的原型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Why does javascript’s “in” operator return true when testing if 0 exists in an array that doesn’t contain 0?4个
我正在阅读 Eloquent JavaScript’s Map section,我无法理解它的最后一段:

If you do have a plain object that you need to treat as a map for some reason,it is useful to know that Object.keys returns only an object’s own keys,not those in the prototype. As an alternative to the in operator,you can use the hasOwnProperty method,which ignores the object’s prototype.

然后我假设Object.keys不返回对象从其原型的继承中获取属性方法.所以我尝试了以下内容

var anObject = {};
console.log(Object.keys(anObject)); //Array []
console.log("toString" in Object.keys(anObject)); //true
console.log(anObject.hasOwnProperty("toString")); //false

显然,toString位于Object.keys(anObject)返回的数组中,但是当我记录其键时会返回一个空数组?我错误地理解了这段经文吗?

解决方法

你正确地理解了这段经文,但这里的用法错误的.

它返回true,因为Object.keys(anObject)返回的Array在其原型中有一个名为toString的属性. in还检查原型,而hasOwnProperty只检查Object实际拥有的属性.

但它没有名为toString的自有属性

let anObject = {};
let keys = Object.keys(anObject);

console.log("toString" in keys); //true
console.log(keys.hasOwnProperty("toString")); //false

猜你在找的JavaScript相关文章