作為一名程序員,我們的工作是寫有效的代碼,但是僅僅寫有效的代碼,這還不夠。如果想成為優秀的程序員,我們還需要編寫可維護和可擴展的代碼。
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
將給定的數組元素添加到調用者數組的末尾。
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: 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
檢查變量是否是數組。
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 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
返回一個新數組,其中所有元素均由給定回調修改。
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 : 4
console.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 : a
console.log(letterIterator.next().value); // Output : b
console.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個數組的全部方法的分享,希望這期內容對你有所幫助。
另外,就是我們在編寫任何處理數組的代碼之前,請考慮可重用性并檢查是否已經存在可以使用的現有方法。
我自己最常用的數組方法是:filter、map、reduce、some 和 every。
如果你也有自己最常用的數組方法,歡迎在留言區給我們大家一起來分享。