简体   繁体   中英

Object.keys() vs Array.prototype.keys()

let arr = new Array(3)
console.log(Object.keys(arr)) // []
console.log([...arr.keys()]) // [0,1,2]

Why is there a difference? It seems that an array in javascript can simultaneously have a length of 3 and be empty. How do you know the behavior of the different functions that operate on sparse lists?

Object.keys() does expect the parameter to be of type object and will cast anything else implicitly to one . Passing an empty array will be casted to an empty object I guess: Object.assign({}, new Array(3)) will give {}

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