Js 中的数组

  在js 中,数组就是对象,除了可以使用字面量语法[...]来声明数组外,它和其它对象没有什么区别。当创建一个数组[‘a’, ‘b’, ‘c’]时,内部的实现形式如下:

{
    length: 3,
    0'a',
    1'b',
    2'c'
}

  可以使用Object.assgin 和对象解构的方式来验证一下

Object.assign({}, [1, 2]); // { '0': 1, '1': 2 }
  let {0: a, 1: b, length} = [1, 2]; // 数字不能作为变量名,需要赋值给其它变量
  console.log(a, b, length); // 1, 1, 2

  当然,这个对象从Array.prototype 继承了map, push 等常用的数组方法。当对数组进行迭代时,比如使用map,它首先看的是length , 然后再开始从零查找对应的每一个元素或属性,直到length 结束。When performing iterative operations like map the array will internally look at its length and then check itself for any properties within the range starting at zero and ending at length. 你可能使用过下面的语法,但发现不起作用,数组arrayA 依然是空。

let arrayA = new Array(3).map(function() { return 1 }); // not work
console.log(arrayA); // still empty

  当使用new Array(3) 创建数组的时候,它并不会创建3个undefined 值,它只是把新创建的数组的length设为了3.  我们可能认为 new Array(3) 的内部实现形式如下:

{
    length: 3,
    0: undefined,
    1: undefined,
    2: undefined,
}

  其实它的内部实现形式如下

{
    length: 3
}

  它只有一个length 属性3,但没有实际的3个值。这些没有存在的值称为holes.  map 对holes 不起作用。This missing values are calls holes. Method like map don’t work on holes。 所以我们试图创建拥有三个值的数组不起作用。可以使用fill 方法,当对数组进行填充的时候,它不管是不是holes. When filling the array, it doesn’t care if at a given index there’s is a value or a hold. 

let arrayA = new Array(3).fill(1);  // work

   创建holes 的另外一种形式是数组字面量中使用,但不给值。比如[1,2,,,,,,,5].   

  不过ES6 增加的方法,如for of,  Array.from, 都把holes 当作undefined 处理

const a = Array.from([,,,]); // Array of 3 holes created with ES6's Array.from()
for (const val of a) {
alert(val === undefined);
}

   数组的toString() 和valueOf() 方法返回相同的值,都是字符串。数组的每一项用,连接

let colors = ["red", "blue", "green"]; // creates an array with three strings
alert(colors.toString()); // red,blue,green
alert(colors.valueOf()); // red,blue,green
原文地址:https://www.cnblogs.com/SamWeb/p/12625435.html