Javascript中的类数组对象

看到一句Javascript的代码:

function test(){
    var args = Array.prototype.slice.call(arguments);
}

第一感觉是这句代码不是多余么?这切分后不是返回一样的数组么?

不过又感觉没人这么蛋疼做这么无聊的事情吧,于是Google,于是发现,我错了!

因为arguments不是一个数组对象,虽然它有length属性,并且你在firebug或者Chrome的控制台log出来的结果和数组一样。

function testArguments(){
    console.log(arguments);  
    console.log(arguments.length);
    console.log(arguments.constructor);
    console.log([].constructor);
    console.log('arguments.slice: ' + arguments.slice);
}

执行结果:

image

看到了吧~~ arguments并不是真正的数组对象。

function test(){
    var args = Array.prototype.slice.call(arguments);
}

所以,这里的Array.prototype.slice.call(arguments);其实是将arguments转换为真正的数组对象的。

参见:http://shifteleven.com/articles/2007/06/28/array-like-objects-in-javascript

啊门!

转载于:https://www.cnblogs.com/QLeelulu/archive/2011/05/05/2038098.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值