类数组的探索

109 阅读1分钟

类数组使用数组方法

1. 什么是类数组

类数组是指具有数字索引下标并且有length属性的对象。 本质是对象!!!

2. 常见的类数组

  • Arguments 函数的参数
  • HTML Collection 根据class或者tag获取到的元素集

3. 如何让类数组可以使用数组的方法

1. 借助call或者apply

Array.prototype.push.call(arguments, 4)
Array.prototype.push.apply(arguments, [4])

2. 利用反柯里化优化
简单说说反柯里优化的作用,当我们调用某个方法,不用考虑这个对象在被设计时,是否拥有这个方法,只要这个方法适用于它,我们就可以对这个对象使用它。
只要在函数原型上添加一个方法uncurrying,以后就方便多了。

Function.prototype.uncurrying = function() {
    let self = this;
    // 这里是拿出参数组中的第一个参数赋值给obj,剩下的参数就是arguments
    return function() {
        let obj = Array.prototype.shift.call(arguments)
        return self.apply(obj, arguments)
      }
}
//mock类数组
let obj = {
    length: 3,
    '0': 'zero',
    '1': 'one',
    '2': 'two'
};
//以下三个方法依次执行 并输出结果
Array.prototype.push.uncurrying()(obj,'three')
console.log(obj) //Object {0: "zero", 1: "one", 2: "two", 3: "three", length: 4}

Array.prototype.shift.uncurrying()(obj)
console.log(obj) //Object {0: "one", 1: "two", 2: "three", length: 3}

Array.prototype.forEach.uncurrying()(obj, function(i, n){
  console.log(i,n)
})//zero 0 one 1 two 2 three 3

4.类数组转化为真正数组

//arguments 就是那个list
(function() {
    console.log(arguments);
    var arr = [...arguments];//转化操作
    console.log(arr);
    // [1,2,3,4]/{ '0': 1, '1': 2, '2': 3, '3': 4 }
})(1,2,3,4,5)
  1. Array.from()方法
let arr = Array.from(list);
  1. 用Array.prototype.slice.call(elems)方法转化为数组
let arr = Array.prototype.slice.call(list);
  1. 用展开符号转化为数组
let  arr = [...list];
  1. 用map,foreach处理
let arr = [];
Array.prototype.forEach.call(arguments,function(item,index,thisValue){
    console.log(item,index,thisValue);
    arr.push(item);
})
Array.prototype.map.call(arguments,function(item,index,thisValue){
    console.log(item,index,thisValue);
    arr.push(item);
})