三、JS的Array

120 阅读12分钟

JS数组原型对象上的方法

整理一下 Array.prototype上的方法。 developer.mozilla.org/zh-CN/docs/…

1. Array.prototype

Array.jpg

2. arr.at(index) 访问数组,和 arr[index]类似。

let a = ['a', 'b', 'c', 'd'];

console.log(a.at(0)); // index >= 0 从左边向右查找
console.log(a.at(-1)); // index < 0 从末尾向开头查找
console.log(a.at(10)); // index 越界 undefined

3. arr1.concat(arr2, [arr3]) 连接(合并)两个或者更多数组

let a = ['a', 'b', 'c', 'd'];

let b = [1, 2, 3];
let a1 = a.concat(b); // 合并成一个新的数组 赋值给 a1
console.log(a); // 原来数组 a 不变
console.log(a1);

4. arr.copyWithin(target, [start = 0, [end = this.length]]) 方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。

参数: target(必需):复制元素的目标位置,即将复制的元素将被粘贴到该位置。如果为负数,则表示从末尾开始计算的索引位置。 start(可选):复制元素的起始位置。如果为负数,则表示从末尾开始计算的索引位置。默认为 0。 end(可选):复制元素的结束位置(不包括该位置)。如果为负数,则表示从末尾开始计算的索引位置。默认为数组长度。

let a = ['a', 'b', 'c', 'd'];
a.copyWithin(1); // 相当于 a.copyWithin(1, 0, 4); 把 0 位置所在的元素a开始,直到数组末尾,在位置1开始拷贝。
console.log(a); // ['a', 'a', 'b', 'c']
let a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.copyWithin(1, 3, 4); // 把 3 这个位置的元素 d 拷贝到 1 这个位置
console.log(a); // ['a', 'd', 'c', 'd', 'e', 'f']

5. arr.entries() 返回一个新的数组迭代器对象,该对象包含数组中每个索引的/键值对。

let a = ['a', 'b', 'c', 'd', 'e', 'f'];
let itera = a.entries();

// 用 for of 遍历
for(let [k, v] of itera) {
    console.log(k, v);
}

6. .arr.every(fn) 方法测试一个数组内的所有元素是否都能通过指定函数的测试。它返回一个布尔值。

let a = ['a', 'b', 'c', 'd', 'e', 'f'];

const result = a.every((element) => {
    console.log(element);

    // 检测数组中的元素是否都等于a,
    if(element === 'a') {
        return true;
    } else {
        return false;
    }
});

console.log(result); // false

7. arr.fill(value, [start = 0, [end = this.length]]) 用一个固定值填充一个数组中从起始索引(默认为 0)到终止索引(默认为 array.length)内的全部元素。它返回修改后的数组。

let a = ['a', 'b', 'c', 'd', 'e', 'f'];
console.log(a.fill(0, 2, 4)); // 把数组 2 和 3 这两个位置填充(修改)为0

8. arr.filter(callbackFn, [thisArg]) 创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素。

let a = [1, 2, 3, 4, 5, 6];

let fn = (item) => item < 5; // 数值小于5的元素,组成一个新数组
let b = a.filter(fn);
console.log(a); // 原数组不变
console.log(b);

9. arr.find(callbackFn, [thisArg ]) 法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。

let a = [1, 2, 3, 4, 5, 6];

let fn = (item) => item == 5;
let b = a.find(fn);
console.log(b); // 5

10. arr.findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。

let a = [1, 2, 3, 4, 5, 6];

let fn = (item) => item == 5;
let b = a.findIndex(fn);
console.log(b); // 4

11. arr.findLast(callbackFn, [thisArg]) 反向迭代数组,并返回满足提供的测试函数的第一个元素的值。如果没有找到对应元素,则返回 undefined。

// findLast对数组的遍历时倒序的,及 6 ~ 1
let a = [1, 2, 3, 4, 5, 6];
let fn = (item) => {
    console.log(item);
};
a.findLast(fn);
// 倒序查找,小于5的第一个元素,
let a = [1, 2, 3, 4, 5, 6];
let fn = (item) => {
    if(item < 5) {
        return true;
    }
    return false
};
let b =a.findLast(fn);
console.log(b); //4

12. arr.findLastIndex(callbackFn, [thisArg]) 反向迭代数组,并返回满足所提供的测试函数的第一个元素的索引。若没有找到对应元素,则返回 -1。

13. arr.flat([depth = 1]) 创建一个新的数组,并根据指定深度递归地将所有子数组元素拼接到新的数组中。

let a = [1, [2, [3, 4]]];
console.log(a); // 数组中是有

let b = a.flat();
console.log(b); // 数组[1, 2, [3, 4]]; 默认只合并一层

let c = a.flat(2);
console.log(c); // [1,2,3,4] // 第二层也合并

14. arr.flatMap(callbackFn, [thisArg]); 方法对数组中的每个元素应用给定的回调函数,然后将结果展开一级,返回一个新数组。

let a = [1, [2, 3], 4, 5];

let fn = (item) => {
    console.log('item = ', item);
    return item * 2; // 看这里,返回的是数字
};
let b = a.flatMap(fn);

console.log(a); // 原数组不变
console.log(b); //  [2, NaN, 8, 10]
let a = [1, [2, 3], 4, 5];

let fn = (item) => {
    console.log('item = ', item);
    return [item * 2]; //看这里返回的是一个数组。最后 b 的数据没变
};
let b = a.flatMap(fn);

console.log(a); // 原数组不变
console.log(b); //  [2, NaN, 8, 10]
let a = [1, [2, 3], 4, 5];

let fn = (item) => {
    console.log('item = ', item);
    return item; // 直接返回的时候,如果时数组,就直接展开了
};
let b = a.flatMap(fn);

console.log(a);
console.log(b); // [1, 2, 3, 4, 5]

15. arr.forEach(callbackFn, [thisArg]) 方法对数组的每个元素执行一次给定的函数。

没有返回值

let a = [1, 2, 3, 4, 5];

let b = a.forEach((item) => {
    return item;
});
console.log(a); // [1, 2, 3, 4, 5]
console.log(b); // undefined 没有 forEach 没有返回值

16. arr.includes(searchElement, [fromIndex = 0]) 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。

参数:
searchElement 需要查找的值。
fromIndex 开始搜索的索引(从零开始)

let a = [1, 2, 3, 4, 5];

console.log(a.includes(5)); // true
console.log(a.includes(10)) // false


console.log(a.includes(2, 1)) // true 从数组的下标为 1 的开始
console.log(a.includes(2, 2)) // false 从数组的下标为 2 的开始

17. arr.indexOf(searchElement, [fromIndex]) 返回数组中第一次出现给定元素的下标,如果不存在则返回 -1。

参数:
searchElement 需要查找的值。
fromIndex 开始搜索的索引(从零开始)

let a = [1, 2, 3, 4, 5];

console.log(a.indexOf(5)); // 4
console.log(a.indexOf(10)) // -1

console.log(a.indexOf(2, 1)) // 1 从数组的下标为 1 的开始 
console.log(a.indexOf(2, 2)) // -1 从数组的下标为 2 的开始,所以没有

18. arr.join([separator]) 一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串,用逗号或指定的分隔符字符串分隔。如果数组只有一个元素,那么将返回该元素而不使用分隔符。

参数:
指定一个字符串来分隔数组的每个元素。默认是逗号","。

let a = [1, 2, 3, 4, 5];

console.log(a.join()); // 1,2,3,4,5
console.log(a.join(" - ")); // 1 - 2 - 3 - 4 - 5

19. arr.keys() 返回一个新的数组迭代器对象,其中包含数组中每个索引的键。

let a = [1, 2, 3, 4, 5];

let iterator = a.keys();
for (const key of iterator) {
  console.log(key); // 0 ~ 5
}

20. arr.lastIndexOf(searchElement, [fromIndex = 0]) 方法返回数组中给定元素最后一次出现的索引,如果不存在则返回 -1。该方法从 fromIndex 开始向前搜索数组。

console.log(a.lastIndexOf('a')); // 4 最后一个出现 a 的下标
console.log(a.lastIndexOf('c')); // 2
console.log(a.lastIndexOf(10)); // -1

21. arr.map(callbackFn, [thisArg]) 方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。

可以和 map() 、flatMap() 对比着看

let a = [1, 2, 3, 4, 5];

let fn = (item) => {
    return item * 2; 
};
let b = a.map(fn); // 会返回一个新的数组

console.log(a); // [1, 2, 3, 4, 5]
console.log(b); // [2, 4, 6, 8, 10]

22. arr.pop()方法从数组中删除最后一个元素,并返回该元素的值。此方法会更改数组的长度。

let a = [1, 2, 3, 4, 5];

let b = a.pop();
console.log(a); // [1, 2, 3, 4] 会修改原数组
console.log(b); // 返回数组中最后一个数据

23. arr.push()

let a = [1, 2, 3, 4, 5];

let b = a.push('a'); // 6 返回长度
console.log(a); // [1, 2, 3, 4, 5, 'a'] 会修改原数组
console.log(b); // 6 


let c = a.push('b', 'c'); // 可以添加多个参数
console.log(a); // [1, 2, 3, 4, 5, 'a', 'b', 'c']

24. arr.reduce(callbackFn, initialValue)

参数:
callbackFn 为数组中每个元素执行的函数。 callbackFn一共有4个参数 callbackFn(accumulator, currentValue, currentIndex, array)

  • accumulator 上一次调用 callbackFn 的结果。
  • currentValue 当前元素的值。
  • currentIndex currentValue 在数组中的索引位置。
  • array 调用了 reduce() 的数组本身。

initialValue 第一次调用回调时初始化 accumulator 的值。

let a = [1, 2, 3, 4, 5];

let b = a.reduce((accumulator, currentValue, currentIndex, array) => {
    console.log(" 上一次调用 callbackFn 的结果 = ", accumulator);
    console.log(" 当前元素的值。 = ", currentValue);
    console.log("currentValue 在数组中的索引位置 = ", currentIndex);
    console.log('-----------');

    return accumulator + currentValue; // // 把数字累加返回
}, 0); // 这个0是累加的初始值

console.log(b); // 15 

25. arr.reduceRight() 对累加器(accumulator)和数组的每个值(按从右到左的顺序)应用一个函数,并使其成为单个值。

26. arr.reverse() 反转数组中的元素,并返回同一数组的引用。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。换句话说,数组中的元素顺序将被翻转,变为与之前相反的方向。

let a = [1, 2, 3, 4, 5];

let b = a.reverse();
console.log(a);
console.log(b);

a.push('a'); // 修改了 a 数组, b也会改变。
// 变量 ab 指向同一个地址。
console.log(a);
console.log(b);

27. arr.shift() 从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

let a = [1, 2, 3, 4, 5];

let b = a.shift();
console.log(a); // 相比原数组,少了开头的元素
console.log(b); // 原数组的第一个元素被弹出

28. arr.slice([start, [end]]) 返回一个新的数组对象,这一对象是一个由 start 和 end 决定的原数组的浅拷贝(包括 start,不包括 end),其中 start 和 end 代表了数组元素的索引。原始数组不会被改变。

参数:

  • start 提取起始处的索引。
  • end 提取终止处的索引。
let a = [1, 2, 3, 4, 5];

console.log('------1.没有参数-----------')
// 1. 没有参数
let b = a.slice();
console.log(a); // [1, 2, 3, 4, 5] 原数组不变
console.log(b); // [1, 2, 3, 4, 5] 返回一个新的数组

console.log('------2. 一个参数-----------')
// 2. 一个参数

//2.1 参数 > 0
let c = a.slice(2);
console.log(c); // [3, 4, 5] 从下标是2开始到最后

//2.1 参数 < 0
let d = a.slice(-2);
console.log(d); // [4, 5] 参数是负,所以从数组的末尾开始数,所以从倒数第二个位置开始,一直到最后

console.log('------3. 两个个参数-----------')

// 两个参数
let e = a.slice(1, 3);
console.log(e); // [2, 3] 从 下边是 1 开始,到下标是3结束。

29. arr.some(callbackFn, [thisArg]) 方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。如果在数组中找到一个元素使得提供的函数返回 true,则返回 true;否则返回 false。它不会修改数组。

let a = [1, 2, 3, 4, 5];

console.log('---------1--------------');
// 1. 先看函数没有返回的情况,其实就是遍历数组
let fn = (item) => {
    console.log('value = ', item);
};
let b = a.some(fn);
console.log(a); // 原数组不变
console.log(b); // false

console.log('---------2--------------');
// 2.
let fn1 = (item) => {
    console.log('value = ', item);
    return true;
};
let c = a.some(fn1); // 函数只执行一次,因为有一个 return 为 true
console.log(c); // true


console.log('---------3--------------');
// 3.
let fn2 = (item) => {
    if(item > 3) {
        return true;
    } else {
        return false;
    }
};
let d = a.some(fn2); // 查找是否有大于3的数字
console.log(d); // true

30. arr.sort([compareFn]) 方法就地对数组的元素进行排序,并返回对相同数组的引用。默认排序是将元素转换为字符串,然后按照它们的 UTF-16 码元值升序排序。

// 没有参数
a.sort();
console.log(a); // [0, 1, 3, 5, 6, 9] 从小到大
2. Array.sort(compareFn); //  sort()方法有参数
compareFn(a, b) < 0a将会被排到b的前面。
compareFn(a, b) = 0,二者相对位置不发生改变。
compareFn(a, b) > 0a将会被排到b的后面。
let a = [5, 1, 9, 6, 0, 3];

let fn = (a, b) => a - b;
let fn1 = (a, b) => b - a;

console.log(a.sort(fn)); // [0, 1, 3, 5, 6, 9]
console.log(a.sort(fn1)); // [9, 6, 5, 3, 1, 0]

31. arr.splice(start, [deleteCount, item1, item2, itemN]) 移除或者替换已存在的元素和/或添加新元素就地改变一个数组的内容。返回被删除的元素组成的数组。

参数: start(必须):指定操作的起始位置,即要添加或删除元素的索引。如果为负数,则表示从末尾开始计算的索引位置。
deleteCount(可选):要删除的元素个数。如果省略该参数,则从起始位置开始删除所有后续元素。
item1, item2, ...(可选):要添加到数组的元素,从起始位置开始插入。

  1. 删除元素
let a = [1, 2, 3, 4, 5];

// 删除 元素
let r = a.splice(1,2); // 从索引1这个位置开始,删除2个元素。返回数组类型,里面的数据是删除的元素。
console.log(a); // [1, 4, 5]
console.log(r); // [2, 3]
  1. 替换元素
let a = [1, 2, 3, 4, 5];

let r = a.splice(1, 2, 'a', 'b', 'c'); // 从索引1这个位置开始,删除2个元素。并在该位置插入 abc这三个元素。 返回数组类型,里面的数据是删除的元素。
console.log(a); // [1, 'a', 'b', 'c', 4, 5]
console.log(r); // [2, 3]
  1. 插入元素
let a = [1, 2, 3, 4, 5];

let r = a.splice(1, 0, 'a', 'b', 'c'); // 从索引1这个位置开始,插入 abc这三个元素。 因为没有删除元素,所以返回一个空数组
console.log(a); // [1, 'a', 'b', 'c', 2, 3, 4, 5]
console.log(r); // []

32. arr.toLocaleString([locales, options]) 用于将数组元素转换为本地化格式的字符串表示,然后返回这个字符串。它将数组的每个元素转换为字符串,并使用逗号分隔它们。可以根据不同的地区和语言环境,生成适合该地区的格式化字符串。

参数:
locales(可选):带有 BCP 47 语言标签的字符串,或者此类字符串的数组。连接
options(可选):一个具有配置属性的对象。

  1. 没有参数
let a = [1, 2, 3, 4, 5];

let b = a.toLocaleString();
console.log(a); // [1, 2, 3, 4, 5]
console.log(b); // 1,2,3,4,5
  1. 有参数
let a = [1, 2, 3, 4, 5];

let b = a.toLocaleString('en-US', {style: 'currency', currency: 'USD'}); // 指定了地区为美国(en-US),使用货币格式化样式。
console.log(a); // [1, 2, 3, 4, 5]
console.log(b); // $1.00,$2.00,$3.00,$4.00,$5.00

33. arr.toReversed() 方法是 reverse() 方法对应的复制版本。它返回一个元素顺序相反的新数组。

let a = [1, 2, 3, 4, 5];

let b = a.toReversed();
console.log(a); // [1, 2, 3, 4, 5]
console.log(b); // [5, 4, 3, 2, 1]

34. arr.toSorted() 是 sort() 方法的复制方法版本。它返回一个新数组,其元素按升序排列。

35. arr.toSpliced() 是 splice() 方法的复制版本。它返回一个新数组,并在给定的索引处删除和/或替换了一些元素。

36. arr.toString() 返回一个字符串,表示指定的数组及其元素。

let a = [1, 2, 3, 4, 5];

let b = a.toString();
console.log(a); // [1, 2, 3, 4, 5]
console.log(b); // 1,2,3,4,5

37. arr.unshift([element1, element2, ...., elementN]) 将指定元素添加到数组的开头,并返回数组的新长度。

let a = [1, 2, 3, 4, 5];

let b = a.unshift('a');
console.log(a); // ['a', 1, 2, 3, 4, 5]
console.log(b); // 6

38. arr.values() 返回一个新的数组迭代器 (en-US)对象,该对象迭代数组中每个元素的值。

let a = [1, 2, 3, 4, 5];

let b = a.values();
console.log(a); // [1, 2, 3, 4, 5]
console.log(b); // 6

for(let value of b) {
    console.log('value = ', value);
}

39. arr.with([index, value]) 方法是使用方括号表示法修改指定索引值的复制方法版本。它会返回一个新数组,其指定索引处的值会被新值替换。

let a = [1, 2, 3, 4, 5];

let b = a.with(1, 'a'); // 把索引1这个位置的元素换成 a
console.log(a); // [1, 2, 3, 4, 5]
console.log(b); // [1, 'a', 3, 4, 5]