自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

42 個通過示例解釋所有 JavaScript 數(shù)組方法

開發(fā) 前端
作為一名程序員,我們的工作是寫有效的代碼,但是僅僅寫有效的代碼,這還不夠。如果想成為優(yōu)秀的程序員,我們還需要編寫可維護和可擴展的代碼。

作為一名程序員,我們的工作是寫有效的代碼,但是僅僅寫有效的代碼,這還不夠。如果想成為優(yōu)秀的程序員,我們還需要編寫可維護和可擴展的代碼。

JavaScript為我們提供了很多可以用來處理數(shù)組的util方法。

今天,就讓我們一起來看看這 42 個數(shù)組方法。

1. at

獲取特定索引處的元素。

負索引表示從末尾開始計數(shù)(例如:-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 : Bob
console.log(nameAtLastIndex); // Output : Joe
console.log(nameAtBeforeLastIndex); // Output : Alice
console.log(nameAtNonExistingIndex); // Output : undefined

2.concat

將給定的數(shù)組元素添加到調(diào)用者數(shù)組的末尾。

const manNames = ["Jhon", "Bob"];
const womanNames = ["Alice"];


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

3. copyWithin

將給定開始索引和結(jié)束索引之間的元素復制到目標索引。

負索引表示從最后一個開始計數(shù)(例如:-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

返回一個迭代器,其中,包含每個數(shù)組元素的索引/值對的數(shù)組。

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

檢查所有數(shù)組元素是否驗證給定條件并返回 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

按給定值從開始索引到結(jié)束索引填充數(shù)組。

負索引表示從最后一個開始計數(shù)(例如:-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

返回僅包含驗證條件的元素的新數(shù)組。

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

在每個元素中展開任何已建立的數(shù)組,并根據(jù)給定的深度級別繼續(xù)展開嵌套的數(shù)組。返回新的平面數(shù)組。

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

返回一個新數(shù)組,其中所有元素均由給定回調(diào)修改,并按 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

迭代數(shù)組并對每個元素應用給定的回調(diào)。

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

從可迭代或類似數(shù)組創(chuàng)建數(shù)組。

/** 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

從異步可迭代、可迭代或類數(shù)組創(chuàng)建數(shù)組。

/** 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

檢查數(shù)組是否包含給定元素。

const letters = ["a", "b", "c"];


console.log(letters.includes("b")); // Output: true
console.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

檢查變量是否是數(shù)組。

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


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

20. join

將所有數(shù)組元素連接到一個字符串,并用給定的分隔符將它們分開。

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 0
console.log(iterator1.next().value); // Output : 1
console.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

返回一個新數(shù)組,其中所有元素均由給定回調(diào)修改。

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

從給定的元素創(chuàng)建一個數(shù)組。

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

25.pop

刪除數(shù)組的最后一個元素并返回它。

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

26. push

將新元素添加到數(shù)組中。

/** 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

通過應用給定的回調(diào)將數(shù)組減少到一個值。給定的回調(diào)應在每次迭代中返回更新的值。

/** 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方法,但從數(shù)組的最后一個元素開始迭代。

/** 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

反轉(zhuǎn)數(shù)組元素的順序。

/** 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

刪除數(shù)組的第一個元素并返回它。

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

31.slice

返回從給定開始到結(jié)束索引的子數(shù)組。

負索引表示從最后一個開始計數(shù)(例如:-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

通過給定的回調(diào)返回排序的數(shù)組。

如果回調(diào)返回正數(shù),則將 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

刪除或替換從給定開始索引到給定結(jié)束索引的子數(shù)組。

負索引表示從最后一個開始計數(shù)(例如:-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

將所有元素轉(zhuǎn)換為語言環(huán)境字符串,將所有元素連接為字符串,同時用逗號分隔每個元素并返回字符串。

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

創(chuàng)建一個新數(shù)組,其中,按相反順序包含調(diào)用方數(shù)組的元素。

它類似于“reverse”方法,但它返回一個新數(shù)組而不修改調(diào)用者數(shù)組。

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

創(chuàng)建一個新數(shù)組,其中包含按給定回調(diào)排序的調(diào)用者數(shù)組的元素。

它類似于“sort”方法,但它返回一個新數(shù)組而不修改調(diào)用者數(shù)組。

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

創(chuàng)建一個新數(shù)組,其中包含調(diào)用方數(shù)組的元素以及已替換或刪除的元素。

它類似于“splice”方法,但它返回一個新數(shù)組而不修改調(diào)用者數(shù)組。

負索引表示從最后一個開始計數(shù)(例如:-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

通過將所有元素連接到字符串,同時用逗號分隔每個元素并返回字符串,將所有元素轉(zhuǎn)換為區(qū)域設(shè)置字符串。

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

將元素添加到數(shù)組中第一個元素之前。

const numbers = [3, 4];


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

41.  values

返回一個迭代器,該迭代器迭代數(shù)組中每個項目的值。

const letters = ["a", "b"];


const letterIterator = letters.values();
console.log(letterIterator.next().value); // Output : a
console.log(letterIterator.next().value); // Output : b
console.log(letterIterator.next().value); // Output : undefined

42.  with

創(chuàng)建一個新數(shù)組,其中包含調(diào)用方數(shù)組的元素以及給定索引處替換的給定值。

負索引表示從最后一個開始計數(shù)(例如:-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"]

結(jié)論

以上就是42個數(shù)組的全部方法的分享,希望這期內(nèi)容對你有所幫助。

另外,就是我們在編寫任何處理數(shù)組的代碼之前,請考慮可重用性并檢查是否已經(jīng)存在可以使用的現(xiàn)有方法。

我自己最常用的數(shù)組方法是:filter、map、reduce、some 和 every。

責任編輯:華軒 來源: web前端開發(fā)
相關(guān)推薦

2022-11-13 15:33:30

JavaScript數(shù)組開發(fā)

2023-07-04 15:52:49

JavaScript數(shù)組

2022-11-23 16:12:57

JavaScript數(shù)據(jù)類型數(shù)組

2019-07-25 10:08:05

JavaScript數(shù)組轉(zhuǎn)換

2020-03-19 15:30:08

JavaScript數(shù)組字符串

2022-05-06 12:03:16

數(shù)組Javascript

2024-03-21 14:27:13

JavaScript數(shù)組

2023-02-01 08:31:48

2022-04-28 08:41:53

JavaScript數(shù)組

2024-08-23 15:34:23

JavaScrip數(shù)組

2025-02-19 12:00:00

JavaScript代碼數(shù)組方法

2022-07-06 10:04:45

JavaScript數(shù)組前端

2022-09-27 14:36:57

JavaScrip數(shù)組開發(fā)

2023-05-08 16:06:33

2025-02-17 11:10:49

2022-10-18 16:35:51

JavaScrip數(shù)組參數(shù)

2022-09-15 08:05:16

緩沖區(qū)類型TypedArray

2016-10-08 21:25:36

Javascript數(shù)組Web

2022-08-10 12:02:52

面試JavaScript

2019-08-13 16:23:19

JavaScript數(shù)組方法
點贊
收藏

51CTO技術(shù)棧公眾號