它看起来像是一个数组,而且它有一个length属性,然则它并非一个数组。JavaScript有时候是一门很奇异的言语,由于你很难定义一个数组的观点而没有什么破例的。
所以我说的这些类数组对象是什么?它们有一些,个中包含arguments
,arguments
是一个很特别的变量,你再一切函数体内都能够访问到。
1. arguments
假如你在一个东西(firebug)中搜检arguments
这个变量,你会注意到它打印出来像是一个数组。它有按序次分列的元素,另有一个length属性。
var testFunction = function() {
console.log(arguments);
console.log(arguments.length);
};
所以我在埋怨什么?尝试arguments.shift()
,报错显现arguments.shift() isn't a function
,然则shift()是数组的一个函数。尝试console.log(arguments.constructor)
,它会打印Object()
,同时假如你输入的是[].constructor
,它会打印Array[]
。这是不是很新鲜?
这固然不仅局限于arguments
,看起来许多DOM鸠合都邑返回这类对象,比方document.getElementsByTagName()
, document.images
, document.childNodes
.在某些情况下,这些相似数组的更适合转变为一个数组。
让类数组对象成为一个数组
固然这个题目是不太正确的,假如我们须要将这些类数组对象变成数组一样,我们须要竖立一个新的数组。
var testFunction = function() {
// Create a new array from the contents of arguments
var args = Array.prototype.slice.call(arguments);
var a = args.shift();
console.log("The first argument is: %s", a);
// send the remaining arguments to some other function
someOtherFunction(args);
};
明显,症结的处所在Array.prototype.slice.call(arguments)
,拆开它细致每一个部份。
Array
这是我们想要的base object的称号prototype
这能够被认为是一个数组实例要领的定名空间slice
提取一个数组的一部份,并返回一个新的数组,没有一个最先和完毕索引,它只返回数组的副本.call
这是一个异常有效的函数,许可你在挪用一个对象的函数,然后在另一个函数的高低文中运用
另一个方面,假如你曾运用原型框架,你能够经由过程$A()
转化这些类数组对象成为数组。
谈到$A
,假如你不喜欢打上面那末长的字符串代码,而且你不运用Prototype。然后,你能够建立一条捷径,就像Prototype folks:
var $A = function(obj) {
return Array.prototype.slice.call(obj);
};
// Example usage:
$A(document.getElementsByTagName("li"));