length
-
Array.length
是有值的,值为1; -
Array.prototype.length
是Array
实例的属性,默认值为0; - 范围为 0 到 232-1 的整数;
const longArr = new Array(2**32 - 1); // (4294967295) [empty × 4294967295]
const negativeArr = new Array(-100); // RangeError: Invalid array length
- 该属性可读可写。如果指定一个更小的
length
时,数组会被截断;如果指定一个更大的length
时,数组长度被修改,成为包含很多空值的稀疏数组,空值为undefined
;
concat
- 定义:合并数组,参数可以是多个,参数如果是数组,会被flat一层再合并,如果是值,直接合并,返回新数组;
- 对于参与合并的数组或元素,是浅拷贝,如果是引用类型的,会统一改变。
let num1 = [[1]];
let num2 = [2, [3]];
let num3=[5,[6]];
let obj = {};
console.log(num1.concat(4, num2, num3)); // [[1], 4, 2, [3], 5, [6]]
num2[1].push('a');
console.log(num2.concat(obj)); // [2, [3, 'a'], {name: 'yn'}]
obj.name = 'yn'
copyWithin
- 定义:复制数组的一部分到其本身,不会修改数组长度,会替换元素。参数:
@params {targetIndex} 要替换的目标位置的起始索引,负数逆序;
@params {startIndex} 要复制部分的起始索引,负数逆序,省略为0, 前闭;
@params {endIndex} 要复制部分的结束索引, 负数逆序,省略则到数组末尾, 后开;
@ return 会改变原数组,返回改变后的数组;
let arr = [1, 2, 3, 4, 5];
arr.copyWithin(-2); // [1, 2, 3, 1, 2]
arr; // [1, 2, 3, 1, 2]
[1, 2, 3, 4, 5].copyWithin(-2, -3, -1) // [1, 2, 3, 3, 4]
[1, 2, 3, 4, 5].copyWithin(0, 3) // [4, 5, 3, 4, 5]
let arr1 = [, , 3, 4, 5];
arr1.copyWithin(0, 1) // [empty, 3, 4, 5, 5]
- 不止用于数组;
[].copyWithin.call({length: 5, 3: 1}, 0, 3); // {0:1, 3: 1,length: 5}
fill
- 定义:用特定值根据索引填充数组,会修改原数组,并返回修改后的数组。参数:
@params{value} 用来填充数组元素的值;
@params{start} 起始索引,默认值0,负数逆序;
@params{end} 结束索引,默认值length - 1,负数逆序;
[1, 2, 3].fill(4, -3, -2); // [4, 2, 3]
Array(3).fill(4); // [4, 4, 4]
[].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}
- 引用类型的填充元素是浅拷贝;
let arr = Array(3).fill({})
arr[0].age = 10;
console.log(arr); // [{age: 10},{age: 10},{age: 10}]
- 索引超出原数组的部分不修改;
[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 5); // [1, 2, 3]
- this不是必须指向数组,可以指向对象;
[].fill.call({length: 3}, 2); // {0: 2, 1: 2, 2: 2, length: 3}
forEach
- 定义: 对数组的每一项执行给定的回调,会自动跳过空值,没有返回值。回调函数可以改变原数组。
const arraySparse = [1,3,,7];
let numCallbackRuns = 0;
arraySparse.forEach( function(element){
console.log(element); // 1 3 7
numCallbackRuns++;
});
console.log("numCallbackRuns: ", numCallbackRuns); // 3
reverse
- 定义: 颠倒数组中元素顺序,并返回该数组。此方法会改变原数组;
const array1 = ['one', 'two', 'three'];
array1.reverse(); // ["three", "two", "one"]
- 颠倒类数组对象
const a = {0: 1, 1: 2, 2: 3, length: 3};
Array.prototype.reverse.call(a);
console.log(a); // {0: 3, 1: 2, 2: 1, length: 3}
sort
- 定义:对数组进行排序,会改变原数组,返回值为排序后的数组.
- 参数为回调函数:
如果不传,将把数组里的每个元素隐式转换为字符串,根据它们的unicode点位进行升序排序;
传入回调,回调函数的参数有两个a和b,返回值的正负决定排列顺序:
(1)返回值<0,则a排在b之前;
(2) 返回值>0,则a排在b后;
(3)返回值=0,则a、b不改变顺序。
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1); // [1, 100000, 21, 30, 4]
const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 3, 4, 5]