skip to Main Content

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


  1. To make it work similarly to how arguments behaves, you’d need to explicitly define a length property on your object:

    console.log(Array.prototype.slice.call( {'0': 'first','1': 'second',length:2}))   
    
    Login or Signup to reply.
  2. 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:

    Array.prototype.slice.call({'0': 'first','1': 'second'})
    

    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:

    console.log(Array.from(Object.values({'0': 'first', '1': 'second'})));
    

    This will give you the desired result [‘first’, ‘second’].

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search