Given that the “arguments” are not a true array, why does Array.prototype.slice.call (arguments) work, but Array.prototype.slice.call (someobject) does not work?

If the arguments are just an object with the length property, then why does it seem to behave differently than other objects without an array, for example, in Array.prototype.slice.

For example, the following code first warns "undefined" and then warns "foo". Why are they different?

(function(a){ var myobj = {0 : "foo"}; var myobjarray = Array.prototype.slice.call(myobj); var argumentsarray = Array.prototype.slice.call(arguments); alert(myobjarray.shift()); alert(argumentsarray.shift()); })("foo"); 
+8
javascript arrays
source share
1 answer

It works if your object has a length property.

 var myobj = { 0: "foo", 1: "bar", length: 2 }; var myobjarray = [].slice.call(myobj); alert(myobjarray.shift()); 

Most array methods depend on the length property. If you try to execute the Array method on an object that does not display the expected interface, you will get unexpected results.

+8
source share

All Articles