简体   繁体   中英

printing properties with Object.keys()

I'm trying to print Object's own properties (not including prototype properties) by using Object.keys() method.

var obj = {
    name : "Jane"
}

keys = Object.keys(obj); //["name"]

when I do

console.log("length" in keys) //It is printing true?

I believe "length" is coming from the prototype . Why does it exist in keys array?

Object.keys() returns an Array and Arrays always have length property .

From Mozilla Documentation.

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Why does it exist in keys array?

It does exists in keys array since keys is an instance of Array and Array has the property length .

This is equivalent of saying

if ( "length" in keys)
{ 
  console.log(true)
}

Check in operator documentation here too.

The in operator returns true if the specified property is in the specified object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM