Javascript 类数组(Array-like)对象

Javascript中的类数组对象(Array-like object)指的是一些看起来像数组但又不是数组的对象。Javascript中的arguments变量、document.getElementsByTagName()返回值就是典型的类数组对象。

类数组特性

  • 类数组对象具有一个length属性且length的值为非负整数。
  • 类数组对象不具有数组对象的方法。例如:push、 pop等方法。

类数组对象可以像数组一样遍历,但不支持数组对象的方法。

function test1() {  
    for(var i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }

    console.log(arguments instanceof Array);
}
test1(2, 3);  
/* 输出
2  
3  
false  
*/

function test2(){  
    arguments.push(1);
}
test2();  
/* 报错
TypeError: undefined is not a function  
*/

将类数组对象转化为数组

slice 方法可以用来将一个类数组(Array-like)对象转换成一个数组。 你只需要用数组原型上的slice方法call这个对象。

function arrayify( a ) {  
    return Array.prototype.slice.call( a );
}

function test3() {  
    var arrayified = arrayify(arguments);
    arrayified.push(1);
    console.log(arrayified);
    console.log(arrayified instanceof Array);
}

test3(2, 3);  
/* 输出
[2, 3, 1]
true  
*/

也可以简单的使用 [].slice.call(a)代替Array.prototype.slice.call(a)

slice 方法可以用来将一个类数组(Array-like)对象/集合转换成一个数组。你只需将该方法绑定到这个对象上。下述代码中 list 函数中的 arguments 就是一个类数组对象。

1 function list() {
2   return Array.prototype.slice.call(arguments);
3 }
4 
5 var list1 = list(1, 2, 3); // [1, 2, 3]

除了使用 Array.prototype.slice.call(arguments),你也可以简单的使用[].slice.call(arguments) 来代替。另外,你可以使用 bind 来简化该过程。

1 var unboundSlice = Array.prototype.slice;
2 var slice = Function.prototype.call.bind(unboundSlice);
3 
4 function list() {
5   return slice(arguments);
6 }
7 
8 var list1 = list(1, 2, 3); // [1, 2, 3]

实例代码

Array.prototype.slice.apply(document.querySelectorAll('.total-con li')).map((item)=>{
          if(item.className == 'hover1') {
            this.sortField = item.getAttribute('sortField')
            this.sortType = item.getAttribute('sortType')
            return
          }
        })
原文地址:https://www.cnblogs.com/timejs/p/5502154.html