最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript數(shù)組常用方法總結(jié)和案例詳解

 更新時(shí)間:2025年08月22日 11:37:14   作者:Yvette-W  
文章總結(jié)了JavaScript數(shù)組常用方法,詳細(xì)對(duì)比參數(shù)、返回值、是否改變?cè)瓟?shù)組及適用場(chǎng)景,幫助開發(fā)者高效選擇方法提升代碼可讀性和性能,感興趣的朋友跟隨小編一起看看吧

includes()

includes 方法用于判斷數(shù)組是否包含某個(gè)指定的元素,它返回一個(gè) 布爾值(true 或 false)。

1.接收參數(shù)

includes 方法接收兩個(gè)參數(shù):

  • 要查找的元素:這是需要在數(shù)組中查找的值(必選)。
  • 從哪里開始查找(可選):指定開始查找的位置,默認(rèn)為 0。

2.返回值

返回 truefalse,表示數(shù)組是否包含指定的元素。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

includes 方法用于檢查數(shù)組是否包含某個(gè)元素,適用于需要快速判斷某個(gè)值是否存在的情況,比 indexOf 更直觀。

5.代碼示例

const arr = [1, 2, 3, 4, 5];
console.log(arr.includes(3)); // true
console.log(arr.includes(6)); // false

6.額外信息

  • includes 可以接受 第二個(gè)參數(shù),指定從哪個(gè)索引開始搜索:
    const arr = [1, 2, 3, 4, 5];
    console.log(arr.includes(2, 2)); // false(從索引2開始找,跳過了2)
    
  • 可以檢查 NaN,而 indexOf 不能:
    const arr = [NaN, 2, 3];
    console.log(arr.includes(NaN)); // true
    console.log(arr.indexOf(NaN));  // -1 (無法找到NaN)
    
  • 對(duì)于對(duì)象引用,includes 只會(huì)匹配 同一個(gè)對(duì)象的引用
    const obj = { a: 1 };
    const arr = [obj, { b: 2 }];
    
    console.log(arr.includes(obj)); // true
    console.log(arr.includes({ b: 2 })); // false(不同的對(duì)象引用)
    

forEach()

forEach 是 JavaScript 數(shù)組的一個(gè)遍歷方法,主要用于對(duì)數(shù)組的每個(gè)元素執(zhí)行指定的回調(diào)函數(shù)。

1.接收參數(shù)

forEach 方法接收一個(gè)回調(diào)函數(shù)作為參數(shù),回調(diào)函數(shù)本身接收三個(gè)參數(shù):

  • 當(dāng)前元素(必選):當(dāng)前遍歷到的元素。
  • 當(dāng)前索引(可選):當(dāng)前元素在數(shù)組中的索引。
  • 原數(shù)組(可選):調(diào)用 forEach 方法的數(shù)組。

2.返回值

返回值是 undefined,即 forEach 不會(huì)返回新數(shù)組,只是對(duì)數(shù)組中的每個(gè)元素執(zhí)行回調(diào)函數(shù)。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 直接改變?cè)瓟?shù)組,但如果回調(diào)函數(shù)內(nèi)部修改了原數(shù)組的元素,數(shù)組內(nèi)容會(huì)被修改。

4.意義

forEach 用于 遍歷數(shù)組并執(zhí)行回調(diào)函數(shù),適用于需要對(duì)數(shù)組元素進(jìn)行操作但不需要返回新數(shù)組的場(chǎng)景。

5.代碼示例

1. 基礎(chǔ)用法

const arr = [1, 2, 3];
arr.forEach((item) => {
  console.log(item * 2); 
});
// 輸出:
// 2
// 4
// 6

2. 修改原數(shù)組(副作用)

const arr = [1, 2, 3];
arr.forEach((item, index, array) => {
  array[index] = item * 2;
});
console.log(arr); // [2, 4, 6] (原數(shù)組被修改)

3. forEach 不能用 return 終止循環(huán) ,如果要提前終止循環(huán),建議用 for...ofsome / every。

const arr = [1, 2, 3];
arr.forEach((item) => {
  if (item === 2) return; // 只會(huì)跳過當(dāng)前這次迭代,不會(huì)終止整個(gè)循環(huán)
  console.log(item);
});
// 輸出:
// 1
// 3

6.額外信息

  • forEach 不會(huì)返回新數(shù)組,如果想要返回一個(gè)新數(shù)組,可以使用 map 代替。
  • 因?yàn)?forEach 不返回新數(shù)組,所以它更適合執(zhí)行某些操作,而不是計(jì)算新數(shù)據(jù)。適用于 副作用操作(如打印日志、修改 DOM),但不適用于需要返回新數(shù)組的情況。

map()

map 是 JavaScript 數(shù)組的一個(gè)常用方法,主要用于 創(chuàng)建一個(gè)新數(shù)組,新數(shù)組中的每個(gè)元素都是由回調(diào)函數(shù)返回的值。

1.接收參數(shù)

map 方法接收一個(gè)回調(diào)函數(shù)作為參數(shù),回調(diào)函數(shù)本身接收三個(gè)參數(shù):

  • 當(dāng)前元素(必選):當(dāng)前遍歷到的元素。
  • 當(dāng)前索引(可選):當(dāng)前元素在數(shù)組中的索引。
  • 原數(shù)組(可選):調(diào)用 map 方法的數(shù)組。

2.返回值

返回一個(gè) 新的數(shù)組,數(shù)組的長(zhǎng)度和原數(shù)組相同,每個(gè)元素都是回調(diào)函數(shù)的返回值。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

map 適用于 基于原數(shù)組生成一個(gè)新數(shù)組 的情況,比如:

  • 數(shù)據(jù)轉(zhuǎn)換(如把數(shù)字?jǐn)?shù)組轉(zhuǎn)換為字符串?dāng)?shù)組)
  • 提取對(duì)象的某個(gè)屬性
  • 對(duì)數(shù)組元素進(jìn)行某種運(yùn)算

5.代碼示例

1. 基礎(chǔ)用法(返回新的數(shù)組,不影響原數(shù)組)

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
console.log(numbers); // [1, 2, 3] (原數(shù)組不變)

2. 處理字符串?dāng)?shù)組(把字符串轉(zhuǎn)換成大寫)

const words = ["hello", "world"];
const upperCaseWords = words.map(word => word.toUpperCase());
console.log(upperCaseWords); // ["HELLO", "WORLD"]

3. 提取對(duì)象的某個(gè)屬性

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 35 }
];
const names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob", "Charlie"]

4. 生成新對(duì)象數(shù)組

const products = [
  { name: "Laptop", price: 1000 },
  { name: "Phone", price: 500 }
];
const withTax = products.map(product => ({
  name: product.name,
  priceWithTax: product.price * 1.2
}));
console.log(withTax);
// [
//   { name: "Laptop", priceWithTax: 1200 },
//   { name: "Phone", priceWithTax: 600 }
// ]

5. 如果回調(diào)函數(shù)沒有顯式返回值,map 會(huì)返回包含 undefined 的新數(shù)組(在新數(shù)組的相應(yīng)位置插入 undefined

const arr = [1, 2, 3];
// 回調(diào)函數(shù)沒有顯式返回值,map 會(huì)返回一個(gè)包含 `undefined` 的新數(shù)組
const result = arr.map((num) => {
  // 沒有返回值
});
console.log(result); // [undefined, undefined, undefined]

6. map 不能用 return 終止循環(huán)。map 的 return 只影響當(dāng)前元素的返回值變成undefined,不會(huì)影響整個(gè)遍歷過程。如果想要提前終止遍歷,考慮使用 some、every、for...offor 循環(huán)。

const arr = [1, 2, 3, 4, 5];
const result = arr.map(num => {
  if (num > 3) return; // 這里的 return 只會(huì)導(dǎo)致當(dāng)前元素變成 undefined
  return num * 2;
});
console.log(result); // [2, 4, 6, undefined, undefined]

如何終止遍歷?

遍歷數(shù)組時(shí)遇到某個(gè)條件就提前停止:

  • some:遇到 return true 時(shí)停止遍歷。
  • every:遇到 return false 時(shí)停止遍歷。
  • for...offor 循環(huán),可以用 break 退出。
const arr = [1, 2, 3, 4, 5];
// some 方法終止遍歷
arr.some(num => {
  console.log(num);
  return num > 3; // 當(dāng) num > 3 時(shí),some 終止遍歷
});
// 輸出: 1 2 3 4

6.額外信息

? 適合數(shù)據(jù)轉(zhuǎn)換,但不適合修改原數(shù)組內(nèi)容。
? 不能提前終止循環(huán),如果需要提前終止,考慮使用 someevery。
? 不會(huì)跳過 undefined 的元素(區(qū)別于 forEach)。

mapvsforEach對(duì)比

特性mapforEach
返回值返回新數(shù)組返回 undefined
修改原數(shù)組不修改不修改(但可以影響原數(shù)組)
適用場(chǎng)景數(shù)據(jù)轉(zhuǎn)換副作用操作(如打印、修改DOM)

示例對(duì)比:

const numbers = [1, 2, 3];
// ? 不推薦用 forEach 生成新數(shù)組
const doubled1 = [];
numbers.forEach(num => doubled1.push(num * 2));
console.log(doubled1); // [2, 4, 6]
// ? 推薦用 map 生成新數(shù)組
const doubled2 = numbers.map(num => num * 2);
console.log(doubled2); // [2, 4, 6]

find()

find 是 JavaScript 數(shù)組的一個(gè)方法,用于查找并返回?cái)?shù)組中 第一個(gè)滿足條件的元素,如果沒有找到,則返回 undefined。

1.接收參數(shù)

都是 接收一個(gè)回調(diào)函數(shù) 作為參數(shù),并且該回調(diào)函數(shù)會(huì)被調(diào)用以處理數(shù)組中的每個(gè)元素。

  • 回調(diào)函數(shù) 接受三個(gè)參數(shù):
    • 當(dāng)前元素(必選)
    • 當(dāng)前索引(可選)
    • 原數(shù)組(可選)

2.返回值

返回值是第一個(gè)滿足條件的元素,如果沒有找到滿足條件的元素,則返回 undefined。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

find 用于 查找數(shù)組中的某個(gè)元素,它會(huì)遍歷數(shù)組,找到第一個(gè)符合條件的元素并返回,適用于需要根據(jù)某些條件快速查找某個(gè)元素的情況。

5.代碼示例

1. 基本用法

const numbers = [1, 2, 3, 4, 5];
const found = numbers.find(num => num > 3);
console.log(found); // 4(第一個(gè)滿足 num > 3 的元素)

2. 找對(duì)象數(shù)組中的元素

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 35 }
];
const foundUser = users.find(user => user.name === "Bob");
console.log(foundUser); // { name: "Bob", age: 30 }

3. 找不到滿足條件的元素

const numbers = [1, 2, 3];
const notFound = numbers.find(num => num > 5);
console.log(notFound); // undefined(沒有滿足條件的元素)

4. find 方法回調(diào)函數(shù)的三個(gè)參數(shù)

const numbers = [1, 2, 3, 4, 5];
const found = numbers.find((num, index, array) => {
  console.log(`當(dāng)前元素:${num}, 當(dāng)前索引:${index}, 原數(shù)組:${array}`);
  return num > 3;
});
console.log(found); 
// 當(dāng)前元素:1, 當(dāng)前索引:0, 原數(shù)組:[1, 2, 3, 4, 5]
// 當(dāng)前元素:2, 當(dāng)前索引:1, 原數(shù)組:[1, 2, 3, 4, 5]
// 當(dāng)前元素:3, 當(dāng)前索引:2, 原數(shù)組:[1, 2, 3, 4, 5]
// 當(dāng)前元素:4, 當(dāng)前索引:3, 原數(shù)組:[1, 2, 3, 4, 5]
// 4

6.額外信息

  • find 只會(huì)返回 第一個(gè)符合條件的元素,如果你需要所有符合條件的元素,應(yīng)該使用 filter。
  • find 一旦找到符合條件的元素,就會(huì) 立即停止遍歷,這與 filter 不同,filter 會(huì)遍歷整個(gè)數(shù)組。

findIndex()

findIndex 是 JavaScript 數(shù)組的一個(gè)方法,它用于 查找數(shù)組中第一個(gè)滿足條件的元素的索引,如果沒有找到,則返回 -1。

1.接收參數(shù)

接收一個(gè)回調(diào)函數(shù) 作為參數(shù),并且該回調(diào)函數(shù)會(huì)被調(diào)用以處理數(shù)組中的每個(gè)元素。

  • 回調(diào)函數(shù) 接受三個(gè)參數(shù):
    • 當(dāng)前元素(必選)
    • 當(dāng)前索引(可選)
    • 原數(shù)組(可選)

2.返回值

返回值是第一個(gè)滿足條件的元素的索引,如果沒有找到,返回 -1。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

findIndex 用于 查找數(shù)組中某個(gè)元素的索引,當(dāng)你需要知道元素的位置時(shí),可以使用 findIndex,而不是直接使用 indexOf 或遍歷數(shù)組。它適用于 查找符合特定條件的元素的索引。

5.代碼示例

1. 基本用法

const numbers = [1, 2, 3, 4, 5];
const index = numbers.findIndex(num => num > 3);
console.log(index); // 3(第一個(gè)滿足 num > 3 的元素索引)

2. 找對(duì)象數(shù)組中的元素的索引

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 35 }
];
const index = users.findIndex(user => user.name === "Bob");
console.log(index); // 1("Bob" 是第一個(gè)符合條件的元素)

3. 找不到滿足條件的元素

const numbers = [1, 2, 3];
const index = numbers.findIndex(num => num > 5);
console.log(index); // -1(沒有符合條件的元素)

4. 使用回調(diào)函數(shù)的三個(gè)參數(shù)

const numbers = [1, 2, 3, 4, 5];
const index = numbers.findIndex((num, index, array) => {
  console.log(`當(dāng)前元素:${num}, 當(dāng)前索引:${index}, 原數(shù)組:${array}`);
  return num > 3;
});
console.log(index); 
// 當(dāng)前元素:1, 當(dāng)前索引:0, 原數(shù)組:[1, 2, 3, 4, 5]
// 當(dāng)前元素:2, 當(dāng)前索引:1, 原數(shù)組:[1, 2, 3, 4, 5]
// 當(dāng)前元素:3, 當(dāng)前索引:2, 原數(shù)組:[1, 2, 3, 4, 5]
// 當(dāng)前元素:4, 當(dāng)前索引:3, 原數(shù)組:[1, 2, 3, 4, 5]
// 3

6.額外信息

  • findIndex 只會(huì)返回 第一個(gè)符合條件的元素的索引,如果你需要所有符合條件的元素的索引,應(yīng)該使用 map 配合 filter ,map生成新索引數(shù)組,不符合條件的索引設(shè)為undefined,filter過濾掉undefined,最終返回符合條件的元素的索引數(shù)組。
  • findIndex 一旦找到符合條件的元素,就會(huì) 立即停止遍歷,和 find 類似。

filter()

filter 是 JavaScript 數(shù)組的一個(gè)方法,它用于 過濾數(shù)組中的元素,返回符合特定條件的新數(shù)組,如果沒有任何元素符合條件,則返回一個(gè)空數(shù)組。

1.接收參數(shù)

filter 方法接收一個(gè)回調(diào)函數(shù)作為參數(shù),該回調(diào)函數(shù)會(huì)對(duì)數(shù)組中的每個(gè)元素進(jìn)行測(cè)試?;卣{(diào)函數(shù)本身接收三個(gè)參數(shù):

  • 當(dāng)前元素(必選):當(dāng)前遍歷到的元素。
  • 當(dāng)前索引(可選):當(dāng)前元素在數(shù)組中的索引。
  • 原數(shù)組(可選):調(diào)用 filter 方法的數(shù)組。

2.返回值

filter 返回一個(gè)新數(shù)組,包含所有通過回調(diào)函數(shù)條件測(cè)試的元素。如果沒有任何元素通過測(cè)試,返回一個(gè)空數(shù)組。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

filter 方法用于過濾數(shù)組中的元素,返回符合特定條件的元素組成的新數(shù)組。它常用于篩選出符合某些標(biāo)準(zhǔn)的元素。

5.代碼示例

const arr = [1, 2, 3, 4, 5];
// 篩選出大于3的元素
const filteredArr = arr.filter(num => num > 3);
console.log(filteredArr); // [4, 5]
// 使用當(dāng)前索引
const arrWithIndex = arr.filter((num, index) => index % 2 === 0);
console.log(arrWithIndex); // [1, 3, 5]
// 過濾出偶數(shù)
const evenNumbers = arr.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]

6.額外信息

  • filter 會(huì)遍歷整個(gè)數(shù)組,即使回調(diào)函數(shù)的某些元素已經(jīng)滿足條件,它仍會(huì)繼續(xù)檢查整個(gè)數(shù)組。
  • 如果回調(diào)函數(shù)返回的是 falseundefined,該元素會(huì)被過濾掉。

indexOf()

indexOf 是 JavaScript 數(shù)組的一個(gè)方法,它用于 查找數(shù)組中某個(gè)元素的第一次出現(xiàn)的索引,如果元素不存在,則返回 -1。

1.接收參數(shù)

indexOf 方法接收兩個(gè)參數(shù):

  • 要查找的元素(必選):要查找的值。
  • 從哪里開始查找(可選):指定從哪個(gè)索引位置開始查找,默認(rèn)為 0。

2.返回值

indexOf 返回?cái)?shù)組中第一個(gè)符合條件的元素的索引,如果沒有找到該元素,則返回 -1。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

indexOf 方法用于查找數(shù)組中某個(gè)元素的第一次出現(xiàn)的索引。它常用于確定元素是否存在于數(shù)組中,并獲取它的位置。

5.代碼示例

const arr = [1, 2, 3, 4, 5];
// 查找元素 3 的索引
console.log(arr.indexOf(3)); // 2
// 查找元素 6 的索引(不存在)
console.log(arr.indexOf(6)); // -1
// 從索引 2 開始查找元素 4
console.log(arr.indexOf(4, 2)); // 3

6.額外信息

  • 如果數(shù)組中有多個(gè)相同的元素,indexOf 只會(huì)返回第一個(gè)匹配的元素的索引。
  • indexOf 方法會(huì)嚴(yán)格比較元素的值(使用 ===),也就是說,如果數(shù)組中存在 1'1',它們會(huì)被認(rèn)為是不相等的。

indexOfvsfindIndex對(duì)比

indexOffindIndex 都是用于查找數(shù)組中元素索引的方法,但它們有一些關(guān)鍵的區(qū)別:

查找條件

  • indexOf:通過值來查找數(shù)組中的元素,要求元素完全匹配。
  • findIndex:通過回調(diào)函數(shù)來查找數(shù)組中的元素,回調(diào)函數(shù)可以定義更復(fù)雜的查找條件,可以對(duì)元素進(jìn)行任意處理或測(cè)試。

參數(shù)

  • indexOf:接收一個(gè)要查找的元素和一個(gè)可選的起始索引。
  • findIndex:接收一個(gè)回調(diào)函數(shù),回調(diào)函數(shù)的返回值決定是否找到匹配元素?;卣{(diào)函數(shù)接收三個(gè)參數(shù):當(dāng)前元素、當(dāng)前索引和原數(shù)組。

查找范圍

  • indexOf:只查找完全匹配的元素。
  • findIndex:可以進(jìn)行自定義條件查找,回調(diào)函數(shù)可以定義任何邏輯來判斷元素是否符合條件。

返回值

  • indexOf:返回元素的第一次出現(xiàn)的索引,若未找到返回 -1。
  • findIndex:返回第一個(gè)使回調(diào)函數(shù)返回 true 的元素的索引,若未找到返回 -1。

代碼示例

const arr = [5, 3, 8, 3, 2];
// indexOf 查找值為 3 的元素
console.log(arr.indexOf(3)); // 1(返回第一個(gè) 3 的索引)
// findIndex 查找大于 4 的元素
console.log(arr.findIndex(num => num > 4)); // 0(返回第一個(gè)大于 4 的元素的索引)
// findIndex 查找第一個(gè)偶數(shù)元素
console.log(arr.findIndex(num => num % 2 === 0)); // 2(返回第一個(gè)偶數(shù)元素 8 的索引)

總結(jié)

  • indexOf 是基于值進(jìn)行查找,并且只能找到完全匹配的元素。
  • findIndex 允許你通過回調(diào)函數(shù)提供復(fù)雜的查找條件,能更靈活地查找符合自定義條件的元素的索引。

lastIndexOf()

lastIndexOf 是 JavaScript 數(shù)組的一個(gè)方法,它用于 查找數(shù)組中某個(gè)元素的最后一次出現(xiàn)的索引,如果元素不存在,則返回 -1。

1.接收參數(shù)

lastIndexOf 方法接收兩個(gè)參數(shù):

  • 要查找的元素(必選):要查找的值。
  • 從哪里開始查找(可選):查找的起始位置,從該索引向左(即從右向左)查找,并包含該索引的元素。默認(rèn)從數(shù)組的末尾開始查找。

2.返回值

lastIndexOf 返回?cái)?shù)組中最后一個(gè)符合條件的元素的索引,如果沒有找到該元素,則返回 -1

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

lastIndexOf 方法用于查找數(shù)組中某個(gè)元素的最后一次出現(xiàn)的索引。它常用于確定元素是否存在于數(shù)組的后半部分或查找元素的最后一次出現(xiàn)位置。

5.代碼示例

const arr = [1, 2, 3, 4, 5, 3, 2];
// 查找元素 3 最后一次出現(xiàn)的索引
console.log(arr.lastIndexOf(3)); // 5
// 查找元素 6 的索引(不存在)
console.log(arr.lastIndexOf(6)); // -1
// 從索引 4(元素是 5)開始,向左查找元素 2
console.log(arr.lastIndexOf(2, 4)); // 1
// 從索引 6(元素 2)開始向左查找
console.log(arr.lastIndexOf(2, 6)); // 6

6.額外信息

  • lastIndexOf 從數(shù)組的末尾開始查找,返回的是最后一個(gè)符合條件的元素的索引。
  • lastIndexOf 是 從 fromIndex 向左(從右向左)查找,并包含 fromIndex 位置的元素。
  • lastIndexOf 會(huì)嚴(yán)格比較元素的值(使用 ===),也就是說,如果數(shù)組中存在 1'1',它們會(huì)被認(rèn)為是不相等的。

every()

every 是 JavaScript 數(shù)組的一個(gè)方法,它用于 檢查數(shù)組中的所有元素是否都滿足指定的條件。如果所有元素都符合條件,則返回 true,否則返回 false。一旦遇到第一個(gè)不滿足條件的元素,就會(huì)停止遍歷(短路機(jī)制)。

1.接收參數(shù)

every 方法接收一個(gè)回調(diào)函數(shù)作為參數(shù),該回調(diào)函數(shù)會(huì)對(duì)數(shù)組中的每個(gè)元素進(jìn)行測(cè)試。回調(diào)函數(shù)本身接收三個(gè)參數(shù):

  • 當(dāng)前元素(必選):當(dāng)前遍歷到的元素。
  • 當(dāng)前索引(可選):當(dāng)前元素在數(shù)組中的索引。
  • 原數(shù)組(可選):調(diào)用 every 方法的數(shù)組。

還可以接收一個(gè) thisArg(可選),用于指定回調(diào)函數(shù)執(zhí)行時(shí)的 this 值。

2.返回值

every 返回一個(gè)布爾值:

  • 如果 所有元素 都滿足回調(diào)函數(shù)的測(cè)試條件,返回 true。
  • 如果 至少有一個(gè)元素 不滿足條件,返回 false(并停止遍歷)。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

every 主要用于判斷數(shù)組中的所有元素是否都符合某個(gè)條件,適用于全體驗(yàn)證的場(chǎng)景。例如:

  • 判斷所有用戶是否已成年
  • 判斷所有訂單是否已支付
  • 判斷所有輸入是否符合格式

5.代碼示例

const arr = [2, 4, 6, 8, 10];
// 判斷所有元素是否大于 3
const allGreaterThanThree = arr.every(num => {
  console.log(num);  // 只會(huì)打印 2
  return num > 3;
});
console.log(allGreaterThanThree); // false (因?yàn)?2 不大于 3,遍歷在遇到 2 時(shí)停止)
// 判斷所有元素是否是偶數(shù)
const allEven = arr.every(num => num % 2 === 0);
console.log(allEven); // true (所有元素都是偶數(shù))
// 使用當(dāng)前索引
const allIndexEven = arr.every((num, index) => index % 2 === 0);
console.log(allIndexEven); // false (索引 1, 3, ... 是奇數(shù))
// 使用 `thisArg`
const obj = { threshold: 5 };
const allGreaterThanThreshold = arr.every(function(num) {
  return num > this.threshold;
}, obj);
console.log(allGreaterThanThreshold); // false (因?yàn)?2 <= 5)

6.額外信息

  • 短路行為every 一旦遇到第一個(gè)不滿足條件的元素,就會(huì)停止遍歷,不會(huì)繼續(xù)檢查后面的元素,直接返回 false。
  • 空數(shù)組:如果數(shù)組為空,every 直接返回 true,因?yàn)闆]有元素違反條件。
  • some 的區(qū)別:
    • every 需要所有元素 滿足條件才返回 true,否則返回 false。
    • some 只要有一個(gè)元素 滿足條件就返回 true,否則返回 false。

some()

some 是 JavaScript 數(shù)組的一個(gè)方法,它用于 檢查數(shù)組中是否至少有一個(gè)元素滿足指定的條件。如果有至少一個(gè)元素符合條件,則返回 true,否則返回 false。一旦找到滿足條件的元素,就會(huì)停止遍歷(短路機(jī)制)。

1.接收參數(shù)

some 方法接收一個(gè)回調(diào)函數(shù)作為參數(shù),該回調(diào)函數(shù)會(huì)對(duì)數(shù)組中的每個(gè)元素進(jìn)行測(cè)試?;卣{(diào)函數(shù)接收三個(gè)參數(shù):

  • 當(dāng)前元素(必選):當(dāng)前遍歷到的元素。
  • 當(dāng)前索引(可選):當(dāng)前元素在數(shù)組中的索引。
  • 原數(shù)組(可選):調(diào)用 some 方法的數(shù)組。

還可以接收一個(gè) thisArg(可選),用于指定回調(diào)函數(shù)執(zhí)行時(shí)的 this 值。

2.返回值

some 返回一個(gè)布爾值:

  • 如果 至少有一個(gè)元素 滿足回調(diào)函數(shù)的條件,返回 true(并立即停止遍歷)。
  • 如果 所有元素 都不滿足條件,返回 false

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

some 主要用于檢查數(shù)組中是否存在符合條件的元素,適用于局部驗(yàn)證的場(chǎng)景。例如:

  • 判斷用戶列表中是否有 VIP 會(huì)員
  • 檢查訂單列表中是否有未支付的訂單
  • 判斷輸入框列表中是否有未填項(xiàng)

5.代碼示例

const arr = [1, 3, 5, 7, 9];
// 判斷是否有偶數(shù)
const hasEven = arr.some(num => {
  console.log(num);  // 依次打印 1, 3, 5, 7, 9
  return num % 2 === 0;
});
console.log(hasEven); // false (數(shù)組中沒有偶數(shù))
// 判斷是否有大于 5 的數(shù)字
const hasGreaterThanFive = arr.some(num => num > 5);
console.log(hasGreaterThanFive); // true (7 和 9 都大于 5)
// 使用當(dāng)前索引
const hasIndexOdd = arr.some((num, index) => index % 2 === 1);
console.log(hasIndexOdd); // true (索引 1, 3, ... 是奇數(shù))
// 使用 `thisArg`
const obj = { threshold: 8 };
const hasGreaterThanThreshold = arr.some(function(num) {
  return num > this.threshold;
}, obj);
console.log(hasGreaterThanThreshold); // true (9 > 8)

6.額外信息

  • 短路行為some 一旦找到滿足條件的元素,就會(huì)停止遍歷,不會(huì)繼續(xù)檢查后面的元素,直接返回 true。
  • 空數(shù)組:如果數(shù)組為空,some 直接返回 false,因?yàn)闆]有元素滿足條件。
  • every 的區(qū)別:
    • some 只要有一個(gè) 元素滿足條件就返回 true,否則返回 false
    • every 需要 所有元素 滿足條件才返回 true,否則返回 false。

some和every在空數(shù)組時(shí)的行為

1. some 在空數(shù)組中的行為

[].some(num => num > 0); // false

為什么是 false?

  • some 的邏輯是 “是否至少有一個(gè)元素滿足條件”。
  • 但空數(shù)組里連一個(gè)元素都沒有,自然不可能有元素滿足條件,所以返回 false。

2. every 在空數(shù)組中的行為

[].every(num => num > 0); // true

為什么是 true

  • every 的邏輯是 “是否所有元素都滿足條件”。
  • 但空數(shù)組里沒有任何元素違反條件,所以從邏輯上講,所有元素(零個(gè)元素)都滿足了條件,因此返回 true。
  • 這個(gè)現(xiàn)象叫做 “真空原則(Vacuous Truth)”,在數(shù)學(xué)和邏輯學(xué)里,如果對(duì)空集的所有元素做某種斷言,那這個(gè)斷言默認(rèn)為 true。

3. 如何更直觀理解?

可以用“考試及格率”來類比:

  • some 相當(dāng)于問:“班級(jí)里至少有一個(gè)學(xué)生及格了嗎?”
    • 如果班級(jí)沒人(空數(shù)組),答案當(dāng)然是 false,因?yàn)檫B學(xué)生都沒有,談不上及格。
  • every 相當(dāng)于問:“班級(jí)里所有學(xué)生都及格了嗎?”
    • 如果班級(jí)沒人(空數(shù)組),那么沒有不及格的學(xué)生,所以默認(rèn)認(rèn)為 所有人都及格,答案是 true。

4. 總結(jié)

方法邏輯空數(shù)組返回值直觀理解
some至少有一個(gè)滿足條件false沒人能滿足條件
every所有都滿足條件true沒有人不滿足條件

push()

push 是 JavaScript 數(shù)組的一個(gè)方法,它用于 向數(shù)組的末尾添加一個(gè)或多個(gè)元素,并返回新數(shù)組的長(zhǎng)度。

1.接收參數(shù)

push(...items)

  • items(必選,1個(gè)或多個(gè)):要添加到數(shù)組末尾的元素,可以是多個(gè)。

2.返回值

返回修改后的數(shù)組的新長(zhǎng)度(即添加新元素后的 length)。

3.是否改變?cè)瓟?shù)組

? 會(huì) 改變?cè)瓟?shù)組(在原數(shù)組末尾添加元素)。

4.意義

  • 用于在數(shù)組末尾追加元素。
  • 常見于構(gòu)建列表動(dòng)態(tài)增加數(shù)據(jù)的場(chǎng)景。

5.代碼示例

const arr = [1, 2, 3];
// 添加一個(gè)元素
const newLength1 = arr.push(4);
console.log(arr); // [1, 2, 3, 4]
console.log(newLength1); // 4
// 添加多個(gè)元素
const newLength2 = arr.push(5, 6, 7);
console.log(arr); // [1, 2, 3, 4, 5, 6, 7]
console.log(newLength2); // 7
// 空數(shù)組使用 push
const emptyArr = [];
emptyArr.push('a', 'b', 'c');
console.log(emptyArr); // ['a', 'b', 'c']

6.額外信息

等價(jià)于 arr[arr.length] = value

const arr = [1, 2, 3];
arr[arr.length] = 4; // 等價(jià)于 arr.push(4)
console.log(arr); // [1, 2, 3, 4]

push 適用于數(shù)組,但不能用于類數(shù)組對(duì)象(如 arguments),除非手動(dòng)綁定:

function test() {
  console.log(arguments.push(4)); // TypeError: arguments.push is not a function
}
test(1, 2, 3);

unshift()

unshift 是 JavaScript 數(shù)組的一個(gè)方法,它用于 在數(shù)組的開頭添加一個(gè)或多個(gè)元素,并返回新數(shù)組的長(zhǎng)度。

1.接收參數(shù)

unshift(...items)

  • items(必選,1個(gè)或多個(gè)):要添加到數(shù)組開頭的元素,可以是多個(gè)。

2.返回值

返回修改后的數(shù)組的新長(zhǎng)度(即添加新元素后的 length)。

3.是否改變?cè)瓟?shù)組

? 會(huì) 改變?cè)瓟?shù)組(在原數(shù)組開頭添加元素)。

4.意義

  • 用于在數(shù)組頭部插入元素,與 push 類似,但作用在數(shù)組前端。
  • 常用于隊(duì)列(FIFO,先進(jìn)先出),或者保持?jǐn)?shù)據(jù)順序的情況下插入新元素。

5.代碼示例

const arr = [3, 4, 5];
// 在數(shù)組開頭添加一個(gè)元素
const newLength1 = arr.unshift(2);
console.log(arr); // [2, 3, 4, 5]
console.log(newLength1); // 4
// 在數(shù)組開頭添加多個(gè)元素
const newLength2 = arr.unshift(0, 1);
console.log(arr); // [0, 1, 2, 3, 4, 5]
console.log(newLength2); // 6
// 空數(shù)組使用 unshift
const emptyArr = [];
emptyArr.unshift('a', 'b', 'c');
console.log(emptyArr); // ['a', 'b', 'c']

6.額外信息

unshift 的性能比 push 差,因?yàn)樗枰苿?dòng)整個(gè)數(shù)組的元素:

const arr = [1, 2, 3, 4, 5];
arr.unshift(0); 
// 需要把 [1,2,3,4,5] 向后移動(dòng),才能插入 0

push 只是在數(shù)組末尾添加,不會(huì)移動(dòng)已有元素,所以如果不需要保證順序,push 更高效。

等價(jià)于 arr.splice(0, 0, ...items),但 unshift 直接返回新長(zhǎng)度,而 splice 返回被刪除的元素(空數(shù)組)。

pop()

pop 是 JavaScript 數(shù)組的一個(gè)方法,它用于 移除并返回?cái)?shù)組的最后一個(gè)元素。

1.接收參數(shù)

不接收任何參數(shù)。

2.返回值

返回被移除的元素
如果數(shù)組為空,則返回 undefined

3.是否改變?cè)瓟?shù)組

? 會(huì) 改變?cè)瓟?shù)組(刪除最后一個(gè)元素)。

4.意義

  • 用于刪除數(shù)組末尾的元素。
  • 適用于**模擬棧(LIFO,后進(jìn)先出)**的操作。

5.代碼示例

const arr = [1, 2, 3, 4];
// 移除最后一個(gè)元素
const lastElement = arr.pop();
console.log(lastElement); // 4
console.log(arr); // [1, 2, 3]
// 繼續(xù)使用 pop
arr.pop();
console.log(arr); // [1, 2]
// 空數(shù)組使用 pop
const emptyArr = [];
console.log(emptyArr.pop()); // undefined
console.log(emptyArr); // []

6.額外信息

pop 只能移除數(shù)組的最后一個(gè)元素,如果想要?jiǎng)h除數(shù)組的其他位置的元素,應(yīng)該使用 splice。

適用于構(gòu)建棧結(jié)構(gòu)

const stack = [];
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.pop()); // 3
console.log(stack.pop()); // 2
console.log(stack.pop()); // 1
console.log(stack.pop()); // undefined (空棧)

shift()

shift 是 JavaScript 數(shù)組的一個(gè)方法,它用于 移除并返回?cái)?shù)組的第一個(gè)元素

1.接收參數(shù)

shift()

  • 不接收任何參數(shù)。

2.返回值

返回被移除的元素。
如果數(shù)組為空,則返回 undefined

3.是否改變?cè)瓟?shù)組

? 會(huì) 改變?cè)瓟?shù)組(刪除第一個(gè)元素)。

4.意義

  • 用于刪除數(shù)組頭部的元素,與 pop 作用相反。
  • 適用于**模擬隊(duì)列(FIFO,先進(jìn)先出)**的操作。

5.代碼示例

const arr = [1, 2, 3, 4];
// 移除第一個(gè)元素
const firstElement = arr.shift();
console.log(firstElement); // 1
console.log(arr); // [2, 3, 4]
// 繼續(xù)使用 shift
arr.shift();
console.log(arr); // [3, 4]
// 空數(shù)組使用 shift
const emptyArr = [];
console.log(emptyArr.shift()); // undefined
console.log(emptyArr); // []

6.額外信息

  • shift 只能移除數(shù)組的第一個(gè)元素,如果想刪除其他位置的元素,可以使用 splice
  • shift 的性能比 pop 差,因?yàn)樗枰苿?dòng)整個(gè)數(shù)組:
const arr = [1, 2, 3, 4, 5];
arr.shift();
// 需要把 [2,3,4,5] 向前移動(dòng),才能刪除 1

pop 只是刪除最后一個(gè)元素,不需要移動(dòng)其他元素,因此如果不要求刪除第一個(gè)元素,pop 更高效。

splice()

splice 是 JavaScript 數(shù)組的一個(gè)方法,它用于 在數(shù)組中刪除、替換或插入元素,并返回被刪除的元素。

1.接收參數(shù)

splice(start, deleteCount, ...items)

  • start(必選):表示從哪個(gè)索引開始操作。
  • deleteCount(可選):表示刪除多少個(gè)元素。如果為 0,則不刪除任何元素。
  • ...items(可選):要插入的新元素(可以是多個(gè))。

2.返回值

返回被刪除的元素組成的數(shù)組。
如果 deleteCount0,則返回空數(shù)組 []

3.是否改變?cè)瓟?shù)組

? 會(huì) 改變?cè)瓟?shù)組(刪除、替換或插入元素)。

4.意義

  • 刪除元素:移除數(shù)組中的一個(gè)或多個(gè)元素。
  • 替換元素:刪除元素的同時(shí),插入新元素。
  • 插入元素:不刪除任何元素,僅插入新元素。

5.代碼示例

(1)刪除元素

const arr = [1, 2, 3, 4, 5];
// 從索引 1 開始,刪除 2 個(gè)元素
const deleted = arr.splice(1, 2);
console.log(arr); // [1, 4, 5]
console.log(deleted); // [2, 3]

(2)替換元素

const arr = [1, 2, 3, 4, 5];
// 替換索引 2 的元素(刪除 1 個(gè)元素,并插入 'A')
const replaced = arr.splice(2, 1, 'A');
console.log(arr); // [1, 2, 'A', 4, 5]
console.log(replaced); // [3]

(3)插入元素

const arr = [1, 2, 3, 4, 5];
// 在索引 2 處插入 'X', 'Y'(不刪除任何元素)
arr.splice(2, 0, 'X', 'Y');
console.log(arr); // [1, 2, 'X', 'Y', 3, 4, 5]

(4)刪除所有元素

const arr = [1, 2, 3, 4, 5];
// 從索引 0 開始刪除所有元素
arr.splice(0, arr.length);
console.log(arr); // []

6.額外信息

  • splice 會(huì)直接修改原數(shù)組,如果不想修改,可以用 slice() 復(fù)制數(shù)組后操作。
  • 常見用法對(duì)比
    • arr.splice(0, 0, ...items) 等價(jià)于 arr.unshift(...items)(在開頭插入元素)。
    • arr.splice(arr.length, 0, ...items) 等價(jià)于 arr.push(...items)(在末尾插入元素)。
    • arr.splice(-1, 1) 等價(jià)于 arr.pop()(刪除最后一個(gè)元素)。
    • arr.splice(0, 1) 等價(jià)于 arr.shift()(刪除第一個(gè)元素)。

注:-1 是從數(shù)組的末尾開始計(jì)數(shù),表示最后一個(gè)元素。負(fù)數(shù)索引非常方便,特別是在需要處理數(shù)組末尾的元素時(shí),避免了手動(dòng)計(jì)算數(shù)組的長(zhǎng)度。

slice()

slice 是 JavaScript 數(shù)組的一個(gè)方法,它用于 返回?cái)?shù)組的一個(gè)淺拷貝,并根據(jù)指定的開始和結(jié)束索引截取元素。

1.接收參數(shù)

slice(start, end)

  • start(可選):表示截取的起始索引(包括該索引)。如果為負(fù)數(shù),則表示從數(shù)組末尾開始計(jì)數(shù)。默認(rèn)值是 0。
  • end(可選):表示截取的結(jié)束索引(不包括該索引)。如果為負(fù)數(shù),則表示從數(shù)組末尾開始計(jì)數(shù)。默認(rèn)值是數(shù)組的長(zhǎng)度。

2.返回值

返回一個(gè)新的數(shù)組,包含從 startend(不包括 end)的元素。如果 startend 超出了數(shù)組的范圍,則會(huì)根據(jù)實(shí)際情況調(diào)整。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

  • slice 用于 從數(shù)組中截取部分元素,生成一個(gè)新的數(shù)組,而不修改原數(shù)組。
  • 它適用于創(chuàng)建數(shù)組的淺拷貝,或者截取數(shù)組的一部分。

5.代碼示例

(1)截取數(shù)組的一部分

const arr = [1, 2, 3, 4, 5];
// 從索引 1 截取到索引 3(不包括索引 3)
const newArr = arr.slice(1, 3);
console.log(newArr); // [2, 3]
console.log(arr); // [1, 2, 3, 4, 5] (原數(shù)組不變)

(2)使用負(fù)數(shù)索引

const arr = [10, 20, 30, 40, 50];
// 從倒數(shù)第二個(gè)元素開始截取
const newArr = arr.slice(-2);
console.log(newArr); // [40, 50]
console.log(arr); // [10, 20, 30, 40, 50] (原數(shù)組不變)

(3)截取整個(gè)數(shù)組的淺拷貝

const arr = [1, 2, 3, 4, 5];
// 截取整個(gè)數(shù)組(即創(chuàng)建一個(gè)淺拷貝)
const newArr = arr.slice();
console.log(newArr); // [1, 2, 3, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5] (原數(shù)組不變)

6.額外信息

  • slice 不修改原數(shù)組,因此是一個(gè) 非破壞性 的方法。
  • slice 也可以用來從字符串中截取字符,因?yàn)樽址灿蓄愃朴跀?shù)組的索引。

slice和...淺拷貝對(duì)比

slice() 和 展開運(yùn)算符 (...) 在 淺拷貝數(shù)組時(shí)作用相同,都可以創(chuàng)建一個(gè)新數(shù)組,而不會(huì)修改原數(shù)組。

const arr = [1, 2, 3];
// 使用 slice() 進(jìn)行淺拷貝
const copy1 = arr.slice();
// 使用展開運(yùn)算符進(jìn)行淺拷貝
const copy2 = [...arr];
console.log(copy1); // [1, 2, 3]
console.log(copy2); // [1, 2, 3]
console.log(copy1 === arr); // false (不是同一個(gè)數(shù)組)
console.log(copy2 === arr); // false (不是同一個(gè)數(shù)組)
特性slice()... 展開運(yùn)算符
語法arr.slice()[...arr]
適用范圍只能用于數(shù)組可以用于數(shù)組、對(duì)象、字符串、NodeList等
深度拷貝淺拷貝(對(duì)象或嵌套數(shù)組仍然共享引用)淺拷貝(對(duì)象或嵌套數(shù)組仍然共享引用)
可額外截取arr.slice(start, end) 可用于提取部分?jǐn)?shù)組僅用于拷貝整個(gè)數(shù)組
  • slice() 可以提取部分?jǐn)?shù)組:
const arr = [1, 2, 3, 4, 5];
const partial = arr.slice(1, 3); // 提取索引 1 到 2
console.log(partial); // [2, 3]
  • 展開運(yùn)算符可以合并數(shù)組(見concat... 合并數(shù)組對(duì)比):
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];
console.log(merged); // [1, 2, 3, 4]
  • 無論使用 slice() 還是 ...,都不會(huì)深拷貝,如果數(shù)組中有對(duì)象,它們?nèi)匀还蚕硪茫?/li>
const arr = [{ name: "Alice" }, { name: "Bob" }];
// 淺拷貝
const copy1 = arr.slice();
const copy2 = [...arr];
// 修改原數(shù)組中的對(duì)象
arr[0].name = "Charlie";
console.log(copy1[0].name); // "Charlie"
console.log(copy2[0].name); // "Charlie"
  • 如果需要深拷貝,可以使用 structuredClone()(現(xiàn)代瀏覽器支持)或 JSON.parse(JSON.stringify(obj))。

總結(jié)

需求建議用法
淺拷貝整個(gè)數(shù)組slice()...
提取部分?jǐn)?shù)組slice(start, end)
合并數(shù)組...(展開運(yùn)算符)
用于類數(shù)組對(duì)象(如 arguments, NodeList)Array.prototype.slice.call(obj)
如果只是單純拷貝數(shù)組,推薦用 展開運(yùn)算符 ([...arr]),更簡(jiǎn)潔。

concat()

concat 是 JavaScript 數(shù)組的一個(gè)方法,它用于 合并兩個(gè)或多個(gè)數(shù)組,并返回一個(gè)新數(shù)組,而不會(huì)修改原數(shù)組。

1.接收參數(shù)

  • valueN(可選):要合并的數(shù)組或值,可以是多個(gè)。

2.返回值

返回一個(gè)新數(shù)組,包含原數(shù)組的元素,以及 concat 傳入的所有參數(shù)的元素。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

concat 方法用于 合并數(shù)組在數(shù)組中添加新元素,常用于需要保持原數(shù)組不變的場(chǎng)景。

5.代碼示例

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// 合并兩個(gè)數(shù)組
const newArr = arr1.concat(arr2);
console.log(newArr); // [1, 2, 3, 4, 5, 6]
// 原數(shù)組未改變
console.log(arr1); // [1, 2, 3]
// 也可以直接添加單個(gè)元素
const newArr2 = arr1.concat(7, 8);
console.log(newArr2); // [1, 2, 3, 7, 8]
// 可以合并多個(gè)數(shù)組
const combinedArr = arr1.concat(arr2, [7, 8, 9]);
console.log(combinedArr); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
// 如果傳入的是對(duì)象,數(shù)組會(huì)包含該對(duì)象的引用
const obj = { a: 1 };
const newArr3 = arr1.concat(obj);
console.log(newArr3); // [1, 2, 3, { a: 1 }]

6.額外信息

  • concat 不會(huì)修改原數(shù)組,而是返回一個(gè)新數(shù)組。
  • 如果 concat 傳入的是對(duì)象或嵌套數(shù)組,它們不會(huì)被深拷貝,而是按引用合并,即修改原對(duì)象會(huì)影響合并后的數(shù)組:
const arr = [1, 2];
const nestedArr = [3, [4, 5]];
const result = arr.concat(nestedArr);
console.log(result); // [1, 2, 3, [4, 5]]
// 修改嵌套數(shù)組
nestedArr[1].push(6);
console.log(result); // [1, 2, 3, [4, 5, 6]]

如上所示,nestedArr 內(nèi)部的數(shù)組 [4, 5]concat 進(jìn) result 后,仍然是引用,所以對(duì) nestedArr[1] 的修改影響了 result。

concat和...合并數(shù)組對(duì)比

展開運(yùn)算符(...) 和 concat() 方法 用于合并數(shù)組的效果是一樣的,它們都可以合并數(shù)組,并返回一個(gè)新的數(shù)組,不修改原數(shù)組。它們都只會(huì)展開第一層,不會(huì)遞歸展開所有層級(jí)。

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// 使用 concat()
const result1 = arr1.concat(arr2);
console.log(result1); // [1, 2, 3, 4, 5, 6]
// 使用展開運(yùn)算符
const result2 = [...arr1, ...arr2];
console.log(result2); // [1, 2, 3, 4, 5, 6]
  • 處理非數(shù)組的情況
const arr = [1, 2, 3];
// 使用 concat() 合并單個(gè)值
const result1 = arr.concat(4);
console.log(result1); // [1, 2, 3, 4]
// 使用 ... 需要手動(dòng)加入單個(gè)值
const result2 = [...arr, 4];
console.log(result2); // [1, 2, 3, 4]
  • 只展開第一層,嵌套數(shù)組不會(huì)自動(dòng)展開
const arr1 = [1, 2];
const arr2 = [3, [4, 5]];
const result = arr1.concat(arr2);
console.log(result); // [1, 2, 3, [4, 5]]
const result2 = [...arr1, ...arr2];
console.log(result2); // [1, 2, 3, [4, 5]]
  • 如何扁平化數(shù)組,展開所有層級(jí)?
    如果想要讓 [4, 5] 也被展開,需要使用 flat()
const result3 = [...arr1, ...arr2.flat()];
console.log(result3); // [1, 2, 3, 4, 5]
const result4 = arr1.concat(arr2.flat());
console.log(result4); // [1, 2, 3, 4, 5]

總結(jié)

  • concat()... 的行為完全一樣,它們只會(huì)展開第一層,不會(huì)遞歸展開所有層級(jí)。
  • 如果想要完全扁平化數(shù)組(展開所有層級(jí)),需要 flat(),無論是 concat() 還是 ...,都可以搭配 flat() 來完成。

reverse()

reverse 是 JavaScript 數(shù)組的一個(gè)方法,它用于 原地反轉(zhuǎn)數(shù)組,即將數(shù)組的元素順序顛倒,并返回修改后的數(shù)組。

1.接收參數(shù)

不接收任何參數(shù)。

2.返回值

返回反轉(zhuǎn)后的原數(shù)組(已修改)。

3.是否改變?cè)瓟?shù)組

? 會(huì) 改變?cè)瓟?shù)組。

4.意義

reverse 用于 原地反轉(zhuǎn)數(shù)組,可以在需要倒序排列數(shù)組元素時(shí)使用。

5.代碼示例

const arr = [1, 2, 3, 4, 5];
// 反轉(zhuǎn)數(shù)組
const reversedArr = arr.reverse();
console.log(reversedArr); // [5, 4, 3, 2, 1]
// 注意:原數(shù)組也被修改
console.log(arr); // [5, 4, 3, 2, 1]

6.額外信息

  • reverse 是一個(gè)破壞性方法,會(huì)直接修改原數(shù)組。如果不想改變?cè)瓟?shù)組,可以先使用 slice()... 復(fù)制一份數(shù)組:
const arr = [10, 20, 30, 40, 50];
// 使用 slice() 復(fù)制數(shù)組后再反轉(zhuǎn)
const newArr1 = arr.slice().reverse();
console.log(newArr1); // [50, 40, 30, 20, 10]
// 使用展開運(yùn)算符復(fù)制數(shù)組后再反轉(zhuǎn)
const newArr2 = [...arr].reverse();
console.log(newArr2); // [50, 40, 30, 20, 10]
  • 如果數(shù)組包含對(duì)象或引用類型,元素順序會(huì)變,但對(duì)象的引用不會(huì)變
const objArr = [{ a: 1 }, { b: 2 }, { c: 3 }];
const reversed = objArr.reverse();
console.log(reversed); 
// [{ c: 3 }, { b: 2 }, { a: 1 }]
console.log(objArr); 
// [{ c: 3 }, { b: 2 }, { a: 1 }]  // 原數(shù)組已修改
// 修改 reversed[0] 也會(huì)影響 objArr[0]
reversed[0].c = 99;
console.log(objArr); 
// [{ c: 99 }, { b: 2 }, { a: 1 }]

sort()

sort 是 JavaScript 數(shù)組的一個(gè)方法,它用于 對(duì)數(shù)組中的元素進(jìn)行排序,并返回排序后的數(shù)組。默認(rèn)情況下,它會(huì)將數(shù)組元素轉(zhuǎn)為字符串后按字符的 Unicode 順序進(jìn)行升序排序。

1.接收參數(shù)

  • compareFunction(可選):sort 方法接受一個(gè)可選的回調(diào)函數(shù)(compareFunction),一個(gè)用來定義排序順序的函數(shù)。該回調(diào)函數(shù)接收兩個(gè)參數(shù) ab,分別代表數(shù)組中的兩個(gè)元素。
    • 如果 compareFunction(a, b) 的返回值 小于 0,a 會(huì)排在 b 前面(即升序排列)。
    • 如果 compareFunction(a, b) 的返回值 大于 0,b 會(huì)排在 a 前面(即降序排列)。
    • 如果 compareFunction(a, b) 的返回值 等于 0,ab 的位置不變。
  • 如果沒有提供,sort 默認(rèn)按字符的 Unicode 編碼順序升序排序。

為什么 arr.sort((a, b) => b - a) 是降序?

在回調(diào)函數(shù) (a, b) => b - a 中:

  • 如果 b - a > 0,b 排在 a 前面。
  • 如果 b - a < 0,a 排在 b 前面。
  • 如果 b - a === 0,ab 的位置保持不變。

因此,b - a 實(shí)現(xiàn)了降序排列,即較大的數(shù)字排在前面。

2.返回值

返回排序后的原數(shù)組(已修改)。

3.是否改變?cè)瓟?shù)組

? 會(huì) 改變?cè)瓟?shù)組。

4.意義

sort 用于 對(duì)數(shù)組元素進(jìn)行排序。它可以按照自定義的順序?qū)?shù)組進(jìn)行升序或降序排列,常用于對(duì)數(shù)據(jù)進(jìn)行排序處理。

5.代碼示例

(1) 默認(rèn)排序(按字符 Unicode 編碼值順序升序排序)

const arr = [3, 1, 4, 5, 2];
// 默認(rèn)排序:按字符的 Unicode 編碼順序排序
arr.sort();
console.log(arr); // [1, 2, 3, 4, 5]
const arrUnicode = [10, 2, 33, 4];
// 注意:數(shù)字直接使用默認(rèn)排序會(huì)出問題,因?yàn)閿?shù)字會(huì)被轉(zhuǎn)換成字符串后,按照字符的 Unicode 編碼順序進(jìn)行排序,數(shù)字字符的排序是逐個(gè)字符比較的。
arr.sort();
console.log(arrUnicode); // [10, 2, 33, 4]

(2) 自定義排序(按數(shù)值升序排序)

const arr = [3, 1, 4, 5, 2];
// 自定義排序:升序排列
arr.sort((a, b) => a - b);
console.log(arr); // [1, 2, 3, 4, 5]

(3) 自定義排序(按數(shù)值降序排序)

const arr = [3, 1, 4, 5, 2];
// 自定義排序:降序排列
arr.sort((a, b) => b - a);
console.log(arr); // [5, 4, 3, 2, 1]

(4) 排序字符串?dāng)?shù)組

const strArr = ['apple', 'banana', 'grape', 'kiwi'];
// 默認(rèn)按字母升序排序
strArr.sort();
console.log(strArr); // ['apple', 'banana', 'grape', 'kiwi']
// 按字母降序排序
strArr.sort((a, b) => b.localeCompare(a));
console.log(strArr); // ['kiwi', 'grape', 'banana', 'apple']

6.額外信息

  • sort破壞性方法,會(huì)直接修改原數(shù)組。如果需要保留原數(shù)組,可以先使用 slice()... 創(chuàng)建一個(gè)副本。
const arr = [3, 1, 4, 5, 2];
const sortedArr = arr.slice().sort((a, b) => a - b);
console.log(sortedArr); // [1, 2, 3, 4, 5]
console.log(arr); // [3, 1, 4, 5, 2]  -- 原數(shù)組未改變
  • sort 對(duì)數(shù)組中的元素按字符 Unicode 順序排序,對(duì)于數(shù)字來說,它是按字符的順序排序,因此會(huì)出現(xiàn)一些問題。為了確保數(shù)字正確排序,可以通過自定義的 compareFunction 來指定排序規(guī)則。
  • 如果數(shù)組中包含對(duì)象,可以根據(jù)對(duì)象的屬性來進(jìn)行排序:
const arr = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 20 }
];
// 按照年齡升序排列
arr.sort((a, b) => a.age - b.age);
console.log(arr);
// [{ name: 'Charlie', age: 20 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]

join()

join() 是 JavaScript 數(shù)組的方法之一,它將數(shù)組的所有元素通過指定的分隔符連接成一個(gè)字符串,并返回這個(gè)新的字符串。

1.接收參數(shù)

分隔符參數(shù)(可選):

  • 如果沒有傳入分隔符,默認(rèn)使用逗號(hào) , 作為分隔符。
  • 如果傳入了分隔符,那么每個(gè)數(shù)組元素之間將使用這個(gè)分隔符進(jìn)行連接。

2.返回值

返回一個(gè)由數(shù)組元素連接成的字符串。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

join() 用于將數(shù)組中的所有元素連接成一個(gè)字符串。這對(duì)于將數(shù)組轉(zhuǎn)換為格式化的字符串(例如 CSV 格式)非常有用。

5.代碼示例

const arr = ['Apple', 'Banana', 'Cherry'];
// 使用逗號(hào)作為分隔符
const result = arr.join();
console.log(result); // "Apple,Banana,Cherry"
// 使用空格作為分隔符
const result2 = arr.join(' ');
console.log(result2); // "Apple Banana Cherry"
// 使用其他分隔符
const result3 = arr.join(' - ');
console.log(result3); // "Apple - Banana - Cherry"

6.額外信息

  • 如果數(shù)組中包含 undefinednull,它們會(huì)被轉(zhuǎn)換為字符串 "undefined""null",而不是空字符串。
  • 如果數(shù)組為空,join() 會(huì)返回一個(gè)空字符串。
const arr = [undefined, null, 5];
console.log(arr.join()); // "undefined,null,5"

new Array(n).join(str)生成重復(fù)字符串

在 JavaScript 中,new Array(n).join(str) 是一種常見的用法,用于生成一個(gè)由 str 重復(fù) n - 1 次組成的字符串。

(1) 為什么是 n - 1 次?

當(dāng)你使用 new Array(n) 創(chuàng)建一個(gè)數(shù)組時(shí),它會(huì)創(chuàng)建一個(gè)長(zhǎng)度為 n 的數(shù)組,但這個(gè)數(shù)組的元素是 空的,即每個(gè)元素都未定義。然后,調(diào)用 join(str) 時(shí),JavaScript 會(huì)將數(shù)組中的元素按 str 進(jìn)行連接。由于數(shù)組中的每個(gè)元素是空的,因此它實(shí)際上會(huì)在 n - 1 次位置插入分隔符 str。

join() 是用來將數(shù)組中的元素連接成字符串的,而空數(shù)組元素并沒有實(shí)際的值,所以它僅根據(jù)數(shù)組的長(zhǎng)度插入相應(yīng)數(shù)量的分隔符。

(2) 代碼示例

const result = new Array(5).join('*');
console.log(result); // "****"
  • new Array(5) 創(chuàng)建了一個(gè)長(zhǎng)度為 5 的空數(shù)組:[empty × 5]。
  • join('*') 將這個(gè)數(shù)組的元素連接成一個(gè)字符串,元素之間用 * 分隔。由于數(shù)組的元素是空的,因此只會(huì)插入 4 個(gè) *(即 n - 1 次)。

(3) repeat()

如果生成一個(gè)由 str 重復(fù)的字符串,不想依賴 join(),可以直接通過 repeat() 方法,這個(gè)方法更直觀。

const result = '*'.repeat(4);
console.log(result); // "****"

reduce()

reduce 是 JavaScript 數(shù)組的一個(gè)方法,它用于 對(duì)數(shù)組中的所有元素執(zhí)行累積操作,最終計(jì)算出一個(gè)單一的值。

1.接收參數(shù)

reduce 方法接受兩個(gè)參數(shù):

  1. 回調(diào)函數(shù) (必填):用于處理數(shù)組的每個(gè)元素,它接受四個(gè)參數(shù):
    • accumulator:累積值,保存上一次迭代的返回值(初始值為 initialValue)。
    • currentValue:當(dāng)前遍歷的元素。
    • currentIndex(可選):當(dāng)前元素的索引。
    • array(可選):調(diào)用 reduce 的原數(shù)組。
  2. 初始值 initialValue(可選):
    • 如果提供,則 accumulator 的初始值為 initialValue,reduce 從索引 0 開始遍歷數(shù)組。
    • 如果省略,則 accumulator 默認(rèn)初始值為數(shù)組的 第一個(gè)元素,遍歷從索引 1 開始。

2.返回值是什么?

返回計(jì)算后的單一值,可以是 數(shù)字、字符串、對(duì)象、數(shù)組等,取決于 reduce 的邏輯。

3.是否改變?cè)瓟?shù)組

? 不會(huì) 改變?cè)瓟?shù)組。

4.意義

reduce 主要用于 數(shù)組求和、計(jì)算平均值、對(duì)象數(shù)組歸類、轉(zhuǎn)換數(shù)據(jù)結(jié)構(gòu)等

5.代碼示例

(1) 求數(shù)組元素的總和

  • 計(jì)算數(shù)組的累加和時(shí),不管是否提供初始值,結(jié)果是一樣的。
  • 在更復(fù)雜的場(chǎng)景中,提供初始值可以避免某些特殊情況,比如空數(shù)組的處理。
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
const sum = numbers.reduce((acc, num) => acc + num);
console.log(sum); // 15

解析:

  • 初始值 acc0
  • 1 + 2 + 3 + 4 + 5 = 15,最終返回 15。

(2) 計(jì)算數(shù)組中的最大值

const nums = [10, 5, 8, 20, 3];
const maxNum = nums.reduce((max, num) => (num > max ? num : max), nums[0]);
console.log(maxNum); // 20

解析:

  • 初始 max 設(shè)為數(shù)組第一個(gè)元素 10。
  • 依次比較 10, 5, 8, 20, 3,最終返回 20

(3) 統(tǒng)計(jì)數(shù)組元素出現(xiàn)次數(shù)

const fruits = ["apple", "banana", "apple", "orange", "banana", "apple"];
const count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});
console.log(count); 
// { apple: 3, banana: 2, orange: 1 }

解析:

  • acc 是一個(gè)對(duì)象,記錄每個(gè)水果的出現(xiàn)次數(shù)。

6.額外信息

如果數(shù)組是空的且未提供 initialValue,會(huì)拋出 TypeError

[].reduce((acc, num) => acc + num); // TypeError

解決方案:提供 initialValue

[].reduce((acc, num) => acc + num, 0); // 0

reduceRight()reduce 類似,但 從數(shù)組的最后一個(gè)元素向前迭代。

到此這篇關(guān)于JavaScript數(shù)組常用方法總結(jié)和案例的文章就介紹到這了,更多相關(guān)js數(shù)組常用方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • JS動(dòng)態(tài)添加與刪除select中的Option對(duì)象(示例代碼)

    JS動(dòng)態(tài)添加與刪除select中的Option對(duì)象(示例代碼)

    本篇文章主要介紹了JS動(dòng)態(tài)添加與刪除select中的Option對(duì)象(示例代碼) 需要的朋友可以過來參考下,希望對(duì)大家有所幫助
    2013-12-12
  • JavaScript常用代碼書寫規(guī)范的超全面總結(jié)

    JavaScript常用代碼書寫規(guī)范的超全面總結(jié)

    這篇文章給大家全面總結(jié)了JavaScript常用代碼的書寫規(guī)范,分別利用推薦和不推薦的兩種示例代碼讓大家更能直接的了解書寫規(guī)范,其實(shí)關(guān)于javascript代碼規(guī)范我們應(yīng)該遵循古老的原則:“能做并不意味著應(yīng)該做”,好了,下面我們就來一起看看吧。
    2016-09-09
  • JavaScript實(shí)現(xiàn)的Tween算法及緩沖特效實(shí)例代碼

    JavaScript實(shí)現(xiàn)的Tween算法及緩沖特效實(shí)例代碼

    這篇文章主要介紹了JavaScript實(shí)現(xiàn)的Tween算法及緩沖特效,涉及JavaScript通過數(shù)學(xué)運(yùn)算及樣式屬性操作實(shí)現(xiàn)緩動(dòng)、彈性運(yùn)動(dòng)等效果,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-11-11
  • 最新評(píng)論

    神农架林区| 绍兴县| 洛宁县| 安远县| 雷山县| 西藏| 禄丰县| 台东县| 邢台县| 明光市| 兴国县| 长治县| 杭锦后旗| 卢氏县| 郯城县| 修武县| 柘荣县| 介休市| 杭州市| 许昌市| 郑州市| 绥棱县| 吉木乃县| 郴州市| 平定县| 望都县| 台湾省| 万山特区| 鹤山市| 甘孜| 濮阳市| 枣庄市| 甘孜| 肥乡县| 建昌县| 德庆县| 天祝| 伊通| 合江县| 全南县| 宁河县|