When I passed object like arguments’ object I receive an empty array. Why?
function checkArguments() {
console.log(arguments)//[Arguments] { '0': 'first', '1': 'second' }
console.log(Array.prototype.slice.call(arguments))//[ 'first', 'second' ]
console.log(Array.prototype.slice.call({'0': 'first','1': 'second'}))// [] ? why empty array
}
checkArguments("first", "second")
2
Answers
To make it work similarly to how arguments behaves, you’d need to explicitly define a length property on your object:
The Array.prototype.slice.call method is expecting an array-like object, meaning an object with a numerical length property and indexed elements starting from 0.
In your example:
The object {‘0’: ‘first’, ‘1’: ‘second’} doesn’t have a length property and isn’t recognized as an array-like object. That’s why you get an empty array.
To convert your custom object to an array, you can use Object.values:
This will give you the desired result [‘first’, ‘second’].