开发者

Given that "arguments" is not a true array, why does Array.prototype.slice.call(arguments) work, but Array.prototype.slice.call(someobject) not work?

开发者 https://www.devze.com 2023-03-15 13:10 出处:网络
If the arguments is just an object with a length property, then why does it seem to behave differently from other non-array objects with respect to, say, Array.prototype.slice.

If the arguments is just an object with a length property, then why does it seem to behave differently from other non-array objects with respect to, say, Array.prototype.slice.

For example, the following code fi开发者_运维问答rst alerts "undefined", and then alerts "foo". Why do these differ?

(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");


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 rely on the length property. If you try to execute an Array method on an object that doesn't expose the expected interface, you'll get unexpected results.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号