42 个通过示例解释所有 JavaScript 数组方法

发布时间:2024年01月01日

今天,就让我们一起来看看这 42?个数组方法。

1. at

获取特定索引处的元素。

负索引表示从末尾开始计数(例如:-1 是最后一个元素)。

const names = ["Jhon", "Bob", "Alice", "Joe"];
const nameAtIndex1 = names.at(1);const nameAtLastIndex = names.at(-1);const nameAtBeforeLastIndex = names.at(-2);const nameAtNonExistingIndex = names.at(10);console.log(nameAtIndex1); // Output : Bobconsole.log(nameAtLastIndex); // Output : Joeconsole.log(nameAtBeforeLastIndex); // Output : Aliceconsole.log(nameAtNonExistingIndex); // Output : undefined

2.concat

将给定的数组元素添加到调用者数组的末尾。

const manNames = ["Jhon", "Bob"];const womanNames = ["Alice"];
const nameConcatenation = manNames.concat(womanNames);console.log(nameConcatenation); // Output : ["Jhon", "Bob", "Alice"]

3. copyWithin

将给定开始索引和结束索引之间的元素复制到目标索引。

负索引表示从最后一个开始计数(例如:-1 是最后一个元素)。

let letters = [];
// Copy to index 1, all elements form the index 3 to index 5 not included ("d" and "e")letters = ["a", "b", "c", "d", "e", "f", "g", "h"];letters.copyWithin(1, 3, 5);console.log(letters);// Output : ["a", "d", "e", "d", "e", "f", "g", "h"]
// Copy to index 1, all elements form the index 3 to end ("d", "e", "f", "g" and "h")letters = ["a", "b", "c", "d", "e", "f", "g", "h"];letters.copyWithin(1, 3);console.log(letters);// Output : ["a", "d", "e", "f", "g", "h", "g", "h"]
// Copy to index -7 (equivalent to 2), all elements from the index -6 (equivalent to 3) to index 5 not included ("d" and "e")letters = ["a", "b", "c", "d", "e", "f", "g", "h"];letters.copyWithin(-7, -6, 5);console.log(letters);// Output : ["a", "d", "e", "d", "e", "f", "g", "h"]

4. ?entries

返回一个迭代器,其中,包含每个数组元素的索引/值对的数组。

const letters = ["a", "b"];
const iterator1 = letters.entries();console.log(iterator1.next().value); // Output [0, 'a']console.log(iterator1.next().value); // Output : [0, 'b']console.log(iterator1.next().value); // Output : undefined

5.?every

检查所有数组元素是否验证给定条件并返回 true。否则,返回 false。

const numbers = [10, 15, 20, 25, 30];
const isAllNumbersBelow40 = numbers.every((number) => number < 40);console.log(isAllNumbersBelow40); // Output : true
const isAllNumbersBelow20 = numbers.every((number) => number < 20);console.log(isAllNumbersBelow20); // Output : false

6.?fill

按给定值从开始索引到结束索引填充数组。

负索引表示从最后一个开始计数(例如:-1 是最后一个元素)。

let numbers = [];
/** Fill 0 on numbers start at index 1 to index 4 not included (3 elements) */numbers = [1, 1, 1, 1, 1];numbers.fill(0, 1, 4);console.log(numbers);// Output : [1, 0, 0, 0, ]
/** Fill 0 on numbers start at index 1 to the end (4 elements) */numbers = [1, 1, 1, 1, 1];numbers.fill(0, 1);console.log(numbers);// Output : [1, 0, 0, 0, 0]
/** Fill 0 on all numbers */numbers = [1, 1, 1, 1, 1];numbers.fill(0);console.log(numbers);// Output : [0, 0, 0, 0, 0]
/** Fill 0 on numbers start at index -4 (equivalent to 2) to index -1 (equivalent to 4) not included (3 elements) */numbers = [1, 1, 1, 1, 1];numbers.fill(0, -4, -1);console.log(numbers);// Output : [1, 0, 0, 0, 1]

7.filter

返回仅包含验证条件的元素的新数组。

const names = ["Joe", "Jhon", "Alice"];
const namesWith4LettersOrLess = names.filter((name) => name.length <= 4);console.log(namesWith4LettersOrLess); // Output : ["Joe", "Jhon"]

8. find

找到第一个验证条件的元素并返回它。否则,返回未定义。

const names = ["Joe", "Jhon", "Alice"];
const firstNameMatchStartWithJ = names.find((name) => name.startsWith("J"));console.log(firstNameMatchStartWithJ); // Output : Joe
const firstNameMatchStartWithK = names.find((name) => name.startsWith("K"));console.log(firstNameMatchStartWithK); // Output : undefined

9. findIndex

找到第一个验证条件的元素并返回其索引。否则,返回-1。

const names = ["Joe", "Jhon", "Alice"];
const firstNameMatchStartWithJ = names.findIndex((name) => name.startsWith("J"));console.log(firstNameMatchStartWithJ); // Output : 0
const firstNameMatchStartWithK = names.findIndex((name) => name.startsWith("K"));console.log(firstNameMatchStartWithK); // Output : -1

10.findLast

找到验证条件的最后一个元素并将其返回。否则,返回未定义。

const names = ["Joe", "Jhon", "Alice"];
const lastNameMatchStartWithJ = names.findLast((name) => name.startsWith("J"));console.log(lastNameMatchStartWithJ); // Output : Jhon
const lastNameMatchStartWithK = names.findLast((name) => name.startsWith("K"));console.log(lastNameMatchStartWithK); // Output : undefined

11. ?findLastIndex

找到最后一个验证条件的元素并返回其索引。否则,返回-1。

const names = ["Joe", "Jhon", "Alice"];
const lastNameMatchStartWithJ = names.findLastIndex((name) => name.startsWith("J"));console.log(lastNameMatchStartWithJ); // Output : 1
const lastNameMatchStartWithK = names.findLastIndex((name) => name.startsWith("K"));console.log(lastNameMatchStartWithK); // Output : -1

12.?flat

在每个元素中展开任何已建立的数组,并根据给定的深度级别继续展开嵌套的数组。返回新的平面数组。

const numbers = [1, 2, [3, [4, [5, 6]]]];
const flatNumbersLevel1 = numbers.flat();console.log(flatNumbersLevel1); // Output : [1, 2, 3, [4, [5, 6]]]
const flatNumbersLevel2 = numbers.flat(2);console.log(flatNumbersLevel2); // Output : [1, 2, 3, 4, [5, 6]]
const flatNumbers = numbers.flat(Infinity);console.log(flatNumbers); // Output : [1, 2, 3, 4, 5, 6]

13. flatMap

返回一个新数组,其中所有元素均由给定回调修改,并按 1 深度级别展平。

const users = [  {    name: "Jhon",    votes: [3, 4]  },  {    name: "Joe",    votes: [4, 5]  }];
const allVotes = users.flatMap((user) => user.votes);console.log(allVotes); // Output : [3, 4, 4, 5]

14. forEach

迭代数组并对每个元素应用给定的回调。

const names = ["Joe", "Jhon", "Alice"];
names.forEach((name, index, array) =>  console.log(`${name} at index ${index} in the array [${array.join(", ")}]`));// Output : Joe at index 0 in the array [Joe, Jhon, Alice]// Output : Jhon at index 1 in the array [Joe, Jhon, Alice]// Output : Alice at index 2 in the array [Joe, Jhon, Alice]

15. ?from

从可迭代或类似数组创建数组。

/** Create an array from string */console.log(Array.from("hello"));// Output : ["h", "e", "l", "l", "o"]
/** Create an array from an other array and apply map method */console.log(Array.from([1, 2, 3], (x) => x * 2));// Output : [2, 4, 6]

16.?fromAsync

从异步可迭代、可迭代或类数组创建数组。

/** Create an array from an array of async elements */const asyncArray = [  new Promise((resolve) => resolve(0)),  new Promise((resolve) => resolve(1))];
(async () => {  const array = await Array.fromAsync(asyncArray);  console.log(array); // Output : [0, 1]})();

17. ?includes

检查数组是否包含给定元素。

const letters = ["a", "b", "c"];
console.log(letters.includes("b")); // Output: trueconsole.log(letters.includes("e")); // Output: false

18. ?indexOf

返回给定元素的第一个匹配项的索引。如果找到任何匹配项,则返回 -1。

const letters = ["a", "b", "c", "d"];
/** Get index of existing letter 'b' */console.log(letters.indexOf("b")); // Output: 1
/** Get index of existing letter 'b' but start searching from index 2 */console.log(letters.indexOf("b", 2)); // Output: -1
/** Get index of existing letter 'b' but start searching from index -4 (equivalent to 0) */console.log(letters.indexOf("b", -4)); // Output: 1
/** Get index of non existing letter 'e' */console.log(letters.indexOf("e")); // Output: -1

19. isArray

检查变量是否是数组。

const array = [];console.log(Array.isArray(array)); // Output : true
const object = {};console.log(Array.isArray(object)); // Output : false

20. join

将所有数组元素连接到一个字符串,并用给定的分隔符将它们分开。

const letters = ["h", "e", "l", "l", "o"];
/** Join all letters together with default separator comma */console.log(letters.join());// Output : h,e,l,l,o
/** Join all letters together with no separator */console.log(letters.join(""));// Output : hello
/** Join all letters together with dash separator */console.log(letters.join("-"));// Output : h-e-l-l-o

21. ?keys

返回包含索引的迭代器。

const letters = ["a", "b"];
const iterator1 = letters.keys();console.log(iterator1.next().value); // Output 0console.log(iterator1.next().value); // Output : 1console.log(iterator1.next().value); // Output : undefined

22.lastIndexOf

返回给定元素的最后一个匹配项的索引。如果找到任何匹配项,则返回 -1。

const letters = ["a", "b", "b", "a"];
/** Get last index of existing letter 'b' */console.log(letters.lastIndexOf("b")); // Output: 2
/** Get index of non existing letter 'e' */console.log(letters.lastIndexOf("e")); // Output: -1

23. map

返回一个新数组,其中所有元素均由给定回调修改。

const numbers = [1, 2, 3];
/** Double all numbers */const doubleNumebrs = numbers.map((number) => number * 2);console.log(doubleNumebrs);// Output : [2, 3, 6]
/** Get number array info */const numberArrayInfo = numbers.map(  (element, index, array) =>    `${element} at index ${index} in the array [${array.join(", ")}]`);console.log(numberArrayInfo);// Output : ["1 at index 0 in the array [1, 2, 3]", "2 at index 1 in the array [1, 2, 3]", "3 at index 2 in the array [1, 2, 3]"]

24. of

从给定的元素创建一个数组。

/** Create an array from values */const numbers = Array.of(1, 2, 3, 4);console.log(numbers);// Output: [1, 2, 3, 4]

25.pop

删除数组的最后一个元素并返回它。

/** Create an array from values */const numbers = [1, 2, 3, 4];console.log(numbers.pop()); // Output : 4console.log(numbers); // Output : [1, 2, 3]

26. push

将新元素添加到数组中。

/** add value or values to the end of array */const numbers = [1, 2, 3, 4];numbers.push(5);numbers.push(6, 7);console.log(numbers);// Output : [1, 2, 3, 4, 5, 6, 7]/** Create an array from values */

27. reduce

通过应用给定的回调将数组减少到一个值。给定的回调应在每次迭代中返回更新的值。

/** Reduce hello array to hello string */const letters = ["h", "e", "l", "l", "o"];const word = letters.reduce((accWord, letter) => `${accWord}${letter}`);console.log(word);// Output : hello

28. reduceRight

它类似于reduce方法,但从数组的最后一个元素开始迭代。

/** Reduce hello array to olleh string */const letters = ["h", "e", "l", "l", "o"];const word = letters.reduceRight((accWord, letter) => `${accWord}${letter}`);console.log(word);// Output : olleh

29. reverse

反转数组元素的顺序。

/** Reverse hello array to olleh array */const letters = ["h", "e", "l", "l", "o"];letters.reverse();console.log(letters);// Output : ["o", "l", "l", "e", "h"]

30.shift

删除数组的第一个元素并返回它。

/** Reverse number order of number array */const numbers = [1, 2, 3];numbers.reverse();console.log(numbers);// Output : [3, 2, 1];

31.slice

返回从给定开始到结束索引的子数组。

负索引表示从最后一个开始计数(例如:-1 是最后一个元素)。

const numbers = ["a", "b", "c", "d", "e"];
/** Get numbers from index 1 to index 4 not included ("b", "c" and "d") */console.log(numbers.slice(1, 4));// Output : ["b", "c", "d"]
/** Get numbers from index 1 to the end ("b", "c", "d" and "e") */console.log(numbers.slice(1));// Output : ["b", "c", "d", "e"]
/** Get numbers from index -4 (equivalent to 1) to index -1 (equivalent to 4) not included ("b", "c" and "d") */console.log(numbers.slice(-4, -1));// Output : ["b", "c", "d"]

32. some

检查是否至少有一个元素验证给定条件。

const numbers = [10, 15, 20, 25, 30];
const isAtLeastOneBelow20 = numbers.some((number) => number < 20);console.log(isAtLeastOneBelow20); // Output : true
const isAtLeastOneBelow5 = numbers.some((number) => number < 5);console.log(isAtLeastOneBelow5); // Output : false

33. ?sort

通过给定的回调返回排序的数组。

如果回调返回正数,则将 a 排序在 b 之后。否则,将 b 排序在 a 之后。

let numbers = [];
/** Sort number in ascendent order. Sort a after b. */numbers = [10, 100, 20, 25, 30];numbers.sort((a, b) => a - b);console.log(numbers); // Output : [10, 20, 25, 30, 100]
/** Sort number in descendant order. Sort b after a */numbers = [10, 100, 20, 25, 30];numbers.sort((a, b) => b - a);console.log(numbers); // Output : [100, 30, 25, 20, 10]

34. splice

删除或替换从给定开始索引到给定结束索引的子数组。

负索引表示从最后一个开始计数(例如:-1 是最后一个元素)。

let numbers = [];
/** Remove elements from index 1 to 3 elements further ([0, 0, 0]) */numbers = [1, 0, 0, 0, 1];numbers.splice(1, 3);console.log(numbers);// Output : [1, 1]
/** Remove elements from index 1 to the end ([0, 0, 0, 1]) */numbers = [1, 0, 0, 0, 1];numbers.splice(1);console.log(numbers);// Output : [1]
/** Remove elements from index -4 (equivalent to 1) to the end ([0, 0, 0, 1]) */numbers = [1, 0, 0, 0, 1];numbers.splice(-4);console.log(numbers);// Output : [1]
/** Replace elements by 2, 2, 2 from index 1 to index 3 included ([0, 0, 0]) */numbers = [1, 0, 0, 0, 1];numbers.splice(1, 3, 2, 2, 2);console.log(numbers);// Output : [1, 2, 2, 2, 1]
/** Replace elements by 2, 2, 2 from index -4 (equivalent to 1) to 3 elements further ([0, 0, 0]) */numbers = [1, 0, 0, 0, 1];numbers.splice(-4, 3, 2, 2, 2);console.log(numbers);// Output : [1, 2, 2, 2, 1]
/** Add elements 2, 2, 2 at index 1 */numbers = [1, 0, 0, 0, 1];numbers.splice(1, 0, 2, 2, 2);console.log(numbers);// Output : [1, 2, 2, 2, 0, 0, 0, 1]

35.?toLocaleString

将所有元素转换为语言环境字符串,将所有元素连接为字符串,同时用逗号分隔每个元素并返回字符串。

const date = [10.4, new Date("31 Aug 2022 22:00:00 UTC")];
console.log(date.toLocaleString());// Output : 10.4,9/1/2022, 12:00:00 AM
console.log(date.toLocaleString("en"));// Output : 10.4,9/1/2022, 12:00:00 AM
console.log(date.toLocaleString("es"));// Output : 10,4,1/9/2022, 0:00:00

36. toReversed

创建一个新数组,其中,按相反顺序包含调用方数组的元素。

它类似于“reverse”方法,但它返回一个新数组而不修改调用者数组。

const numbers = [1, 2, 3];
const reversedNumbers = numbers.toReversed();
console.log(reversedNumbers); // Output : [3, 2, 1]console.log(numbers); // Output : [1, 2, 3]

37. toSorted

创建一个新数组,其中包含按给定回调排序的调用者数组的元素。

它类似于“sort”方法,但它返回一个新数组而不修改调用者数组。

const numbers = [10, 100, 20, 25, 30];
/** Sort number in ascendent order. Sort a after b. */const numbersInAscOrder = numbers.toSorted((a, b) => a - b);console.log(numbersInAscOrder); // Output : [10, 20, 25, 30, 100]console.log(numbers); // Output : [10, 100, 20, 25, 30]
/** Sort number in descendant order. Sort b after a */const numbersInDescOrder = numbers.toSorted((a, b) => b - a);console.log(numbersInDescOrder); // Output : [100, 30, 25, 20, 10]console.log(numbers); // Output : [10, 100, 20, 25, 30]

38. toSpliced

创建一个新数组,其中包含调用方数组的元素以及已替换或删除的元素。

它类似于“splice”方法,但它返回一个新数组而不修改调用者数组。

负索引表示从最后一个开始计数(例如:-1 是最后一个元素)。

let numbers = [1, 0, 0, 0, 1];
/** Remove elements from index 1 to 3 elements further ([0, 0, 0]) */const splicedNumbers1 = numbers.toSpliced(1, 3);console.log(splicedNumbers1); // Output : [1, 1]console.log(numbers); // Output : [1, 0, 0, 0, 1]
/** Replace elements by 2, 2, 2 from index 1 to index 3 included ([0, 0, 0]) */const splicedNumbers2 = numbers.toSpliced(1, 3, 2, 2, 2);console.log(splicedNumbers2); // Output : [1, 2, 2, 2, 1]console.log(numbers); // Output : [1, 0, 0, 0, 1]
/** Add elements 2, 2, 2 at index 1 */const splicedNumbers3 = numbers.toSpliced(1, 0, 2, 2, 2);console.log(splicedNumbers3); // Output : [1, 2, 2, 2, 0, 0, 0, 1]console.log(numbers); // Output : [1, 0, 0, 0, 1]

39. ?toString

通过将所有元素连接到字符串,同时用逗号分隔每个元素并返回字符串,将所有元素转换为区域设置字符串。

const letters = ["a", "b", "c", "d"];
/** Join all letters together with default separator comma */console.log(letters.toString());// Ouput : a,b,c,d

40. unshift

将元素添加到数组中第一个元素之前。

const numbers = [3, 4];
numbers.unshift(0, 1, 2);console.log(numbers); // Output : [0, 1, 2, 3, 4]

41. ?values

返回一个迭代器,该迭代器迭代数组中每个项目的值。

const letters = ["a", "b"];
const letterIterator = letters.values();console.log(letterIterator.next().value); // Output : aconsole.log(letterIterator.next().value); // Output : bconsole.log(letterIterator.next().value); // Output : undefined

42. ?with

创建一个新数组,其中包含调用方数组的元素以及给定索引处替换的给定值。

负索引表示从最后一个开始计数(例如:-1 是最后一个元素)。

const letters = ["a", "k", "c", "d"];
/** replace k at index 1 with b */console.log(letters.with(1, "b"));// Output : ["a", "b", "c", "d"]
/** replace k at index -3 (equivalent to 1) with b */console.log(letters.with(-3, "b"));// Output : ["a", "b", "c", "d"]

结论

以上就是42个数组的全部方法

文章来源:https://blog.csdn.net/qq_33834489/article/details/135325575
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。