你真的了解JS中的数组吗?——类数组

81 阅读1分钟

首先我们看一下类数组的数据结构

  1. 使用数字作为属性名称
  2. 需要具备 length 属性
const obj = {
  0: "a",
  1: "b",
  2: "c",
  3: "d",
  4: "e",
  length: 5,
};

然后聊聊 JavaScript 为什么需要类数组

我们常见的类数组 arguments 对象

function sum(a, b) {
  console.log(arguments); //Arguments(2) [1, 2, callee: ƒ, Symbol(Symbol.iterator): ƒ]
  arguments.push(3); //Uncaught TypeError: arguments.push is not a function
}
sum(1, 2);
  • 如果 arguments 是一个数组,那么 arguments 就容易被开发者随意篡改。
  • 如果 arguments 是一个普通的对象,那么操作起来又过于复杂,且对象需要键值对,没办法确定 key 值。
  • 所以类数组能够轻易的转换成数组进行操作,而且直接修改的代价比数组大的多

最后,来看一下类数组如何转换成数组

  1. Array.from
function sum(a, b) {
  const arr = Array.from(arguments); // ES6 类数组转化成数组
  console.log(arr); // [1,2]
}
sum(1, 2);
  1. 扩展运算符
function sum(a, b) {
  for (let i in arguments) {
    console.log(arguments[i]);
  }

  const arr = [...arguments]; // ES6 类数组转化成数组
  console.log(arr); // [1,2]
}
sum(1, 2);
  1. 数组原型的方法运用在类数组上
function sum(a, b) {
  const arr = Array.prototype.slice.call(arguments); // ES6 类数组转化成数组
  // 类似的还有
  // Array.prototype.concat.apply([],arguments)
  // Array.prototype.splice.call(arguments,0)
  console.log(arr); // [1,2]
}
sum(1, 2);
  1. 循环操作
function sum(a, b) {
  const arr = [];
  for (let i in arguments) {
    arr.push(arguments[i]);
  }
  console.log(arr); // [1,2]
}
sum(1, 2);
``;