javascript的Array-like对象

作者:kun10 发布时间:May 3, 2011 分类:JavaScript

什么是javascript里面的ArrayLike对象?
一切都是源于看YUI的Array部分,Y.Array()方法本身就能把对象转化为数组的方法,接受一个叫arraylike的参数。
其实arraylike我们经常会遇到,函数的arguments对象就是一个最常见的arraylike对象。
我们可以在firebug里面console.log一个函数的arguments对象,会发现他是一个对象,不是会发现他带有一个length属性。
但是我们却不能用普通的数组的方法来操作arguments对象
比如:

arguments.pop();//arguments.pop is not a function

很奇特吧?其实arraylike的对象还不只arguments对象一个
document.getElementsByTagName(), document.images, document.childNodes这几个货都是arraylike的对象。
既然这些对象是arraylike的,我们自然很渴望使用array的方法来操作他们。
方法很早就有人写了。

var newArray = Array.prototype.slice.call(arguments);

原理:
Array.prototype.slice: The original slice method that is given to all arrays via the prototype chain. We can’t call it directly though, because when it runs internally, it looks at the this keyword, and calling it here would make this point to Array, not our arguments variable.
Array.prototype.slice.call(): call() and apply() are prototype methods of the Function object, meaning that they can be called on every function in javascript. These allow you to change what the this variable points to inside a given function.

中文注解:
Array.prototype.slice是Array原型上面的slice方法,因为Arraylike对象不是array,所以直接使用slice是无效的,因此我们要把我们的arguments对象作为this,传入slice方法中。如何传入slice方法,我们使用call方式来把arguments作为this传给slice做处理。call和apply是Function构造函数对象的原型方法,因此我们可以对任意的函数使用。this最终被函数处理成一个数组。

这在非IE的情况下面好使,因为在IE下面domnodelist不被认为是对象,对于IE我们只能使用慢一点的方法了。

var newArray = [];
for(var i = 0;i< arguments.length;i++){
    arr.push(arguments[i]);
}
return newArray;

此时newArray就是一个数组对象。
我们可以对他pop(),push()等等等等。。。
参考:
http://nfriedly.com/techblog/2009/06/advanced-javascript-objects-arrays-and-array-like-objects/(这篇更靠谱点。。。)
http://shifteleven.com/articles/2007/06/28/array-like-objects-in-javascript

  1. 1