Vino
Vino

Reputation: 304

Internal working of Array.prototype.slice.call()

As we know, we use Array.prototype.slice.call() in scenarios like converting function arguments into Array.

Now, if im trying to do the same with some other object, which has key values iterated in numerical way, along with a non-numeric key value, its omitting it.(non-numeric). Below is the code.

var myobject ={ // array-like collection
length: 4,
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three'
}

var myarray = Array.prototype.slice.call(myobject) // returns myobject  as a true array: ["zero", "one", "two", "three"]

The same flow, if im using an object only with key values like 0,1,2,3... empty array is returned. Below is the code.

var myobject2 ={ // array-like collection

'1': 'one',
'2': 'two',
'3': 'three'
}

var myarray2 = Array.prototype.slice.call(myobject2) //returns empty array

Can anybody please explain why this is happening???? Does it looks only on numeric keys , creates empty array and converts it into numeric indices??????

Upvotes: 1

Views: 59

Answers (1)

jfriend00
jfriend00

Reputation: 707298

Array.prototype.slice.call() requires a .length property and then a corresponding zero-based number of numeric properties (though all property names are actually strings so it's the string equivalent of numbers). If it doesn't find those present, it does not do the .slice() properly.

If the source is not an actual array, then it basically just goes into a loop from 0 to .length - 1 look for matching property names on the object and copies any value it finds with that property name. The property names must match the string equivalent of the numbers exactly.

Any missing numeric properties are simply copied as undefined since that's what their value is.

Upvotes: 3

Related Questions