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

啊门!

posted on 2011-05-05 17:40  Q.Lee.lulu  阅读(4089)  评论(0编辑  收藏  举报