19個JavaScript數(shù)組常用方法總結(jié)! 趕快收藏吧!
數(shù)組,是JavaScript中的一種數(shù)據(jù)格式,在JavaScript中經(jīng)常使用。作為一名前端工程師,掌握Array的用法非常重要!
那么,常用的數(shù)組方法你知道幾個呢?
如果不知道也沒有關(guān)系,今天這篇文章將匯總詳細(xì)介紹Array中常用的一些方法,一起來學(xué)習(xí)一下吧!
01、push
功能:向數(shù)組末尾添加一個或多個元素,并返回數(shù)組的新長度。
//push()
arry.push(element1,element2,...,elementN)
參數(shù)說明:element1、element2、…、elementN 是要添加到數(shù)組末尾的元素。
用法示例:
1. 將單個元素添加到數(shù)組末尾;
const numbers = [1, 2, 3];
const length = numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]
console.log(length); // 4
2、向數(shù)組末尾添加多個元素;
const fruits = ['apple', 'banana'];
fruits.push('kiwi', 'orange');
console.log(fruits); // ['apple', 'banana', 'kiwi', 'orange']
02、pop
功能:刪除并返回數(shù)組最后一個元素
//pop()
arry.pop()
注意:pop()方法會修改原數(shù)組,并將數(shù)組長度減一。
用法示例:
const fruits = ['apple', 'banana', 'kiwi'];
const removedElement = fruits.pop();
console.log(fruits); // ['apple', 'banana']
console.log(removedElement); // 'kiwi'
使用pop方法刪除數(shù)組的最后一個元素;
03、shift
功能:刪除并返回數(shù)組的第一個元素
//shift()
array.shift()
用法示例:
1、使用shift刪除元素,bing返回刪除的元素;
const fruits = ['apple', 'banana', 'kiwi'];
const removedElement = fruits.shift();
console.log(fruits); // ['banana', 'kiwi']
console.log(removedElement); // 'apple'
2.如果刪除空數(shù)組,結(jié)果將返回undefined;
const emptyArray = [];
const removedElement = emptyArray.shift();
console.log(emptyArray); // []
console.log(removedElement); // undefined
04、unshif
功能:向數(shù)組開頭添加一個或多個元素,并返回數(shù)組的新長度
//unshif()
arry.unshif(element1,element2,...,elementN)
element1、element2、...、elementN 是要添加到數(shù)組開頭的元素。
用法示例:
1.基本用法,添加單個元素;
const numbers = [2, 3, 4];
const length = numbers.unshift(1);
console.log(numbers); // [1, 2, 3, 4]
console.log(length); // 4
2.添加多個元素;
const fruits = ['banana', 'orange'];
fruits.unshift('apple', 'kiwi');
console.log(fruits); // ['apple', 'kiwi', 'banana', 'orange']
05、concat
功能:將兩個或多個數(shù)組合并成一個新數(shù)組
value1, value2, …, valueN 是要連接的數(shù)組或值。
用法示例:
1. 連接兩個陣列:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const concatenatedArray = array1.concat(array2);
console.log(concatenatedArray); // [1, 2, 3, 4, 5, 6]
2. 連接數(shù)組和值:
const array = [1, 2, 3];
const value = 4;
const concatenatedArray = array.concat(value);
console.log(concatenatedArray); // [1, 2, 3, 4]
3. 連接多個陣列:
const array1 = [1, 2];
const array2 = [3, 4];
const array3 = [5, 6];
const concatenatedArray = array1.concat(array2, array3);
console.log(concatenatedArray); // [1, 2, 3, 4, 5, 6]
06、slice
功能:從數(shù)組中提取指定范圍的元素并返回一個新數(shù)組
//splice
array.slice(start,end)
參數(shù)說明:
- start 為提取元素起始位置的索引(包括該索引對應(yīng)的元素);
- end 是提取元素結(jié)束位置的索引(不包括該索引對應(yīng)的元素);
如果未指定 end 參數(shù),則提取從起始索引位置到數(shù)組末尾的所有元素。
用法示例:
1、提取指定范圍內(nèi)的元素:
const fruits = ['apple', 'banana', 'kiwi', 'orange', 'grape'];
const slicedElements = fruits.slice(1, 4);
console.log(slicedElements); // ['banana', 'kiwi', 'orange']
2、提取指定位置到數(shù)組末尾的元素:
const numbers = [1, 2, 3, 4, 5];
const slicedElementsToEnd = numbers.slice(2);
console.log(slicedElementsToEnd); // [3, 4, 5]
3.復(fù)制數(shù)組:
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = originalArray.slice();
console.log(copiedArray); // [1, 2, 3, 4, 5]
07、splice
功能:刪除、替換或添加元素到數(shù)組的指定位置
//splice()
array.splice(start,deleteCount,item1,item2,...)
參數(shù)說明:
- start 是要修改的起始位置的索引;
- deleteCount 是要刪除的元素數(shù)。
您可以根據(jù)需要指定item1、item2等參數(shù)來插入新元素。
如果未指定deleteCount,則刪除從起始索引位置開始的所有元素。
用法示例:
1、刪除元素:
const numbers = [1, 2, 3, 4, 5];
const deletedElements = numbers.splice(2, 2);
console.log(numbers); // [1, 2, 5]
console.log(deletedElements); // [3, 4]
2. 更換元素:
const fruits = ['apple', 'banana', 'kiwi'];
const replacedElements = fruits.splice(1, 1, 'orange', 'grape');
console.log(fruits); // ['apple', 'orange', 'grape', 'kiwi']
console.log(replacedElements); // ['banana']
3.插入元素:
const colors = ['red', 'blue', 'green'];
colors.splice(1, 0, 'yellow', 'purple');
console.log(colors); // ['red', 'yellow', 'purple', 'blue', 'green']
08、join
功能:使用指定的分隔符將數(shù)組中的所有元素連接成字符串
//join()
array.join(separator)
分隔符是可選字符串參數(shù),指定元素之間的分隔符,默認(rèn)為逗號(,)。
用法示例:
1、數(shù)組之間用“-”分隔;
const fruits = ['apple', 'banana', 'kiwi'];
const joinedString = fruits.join('-');
console.log(joinedString); // "apple-banana-kiwi"
2.默認(rèn)使用逗號作為分隔符;
const numbers = [1, 2,
3, 4, 5];
const joinedStringDefault = numbers.join();
console.log(joinedStringDefault); // "1,2,3,4,5"
09、indexOf
功能:返回指定元素在數(shù)組中第一次出現(xiàn)的索引,如果沒有找到則返回-1。
//indexOf()
array.indexOf(searchElement,formIndex)
1、搜索下標(biāo)位置第一次出現(xiàn)的位置;
const fruits = ['apple', 'banana', 'kiwi', 'banana', 'orange'];
const index = fruits.indexOf('banana');
console.log(index); // 1
2、查找指定位置的下標(biāo)位置;
const numbers = [1, 2, 3, 4, 5, 3, 2, 1];
const indexFromIndex = numbers.indexOf(3, 3);
console.log(indexFromIndex); // 5
10、lastIndexOf
功能:返回數(shù)組中最后一次出現(xiàn)的指定元素的索引,如果沒有找到則返回-1
//lastIndexOf()
array.lastIndexOf(searchElement,formIndex)
用法示例:
1、搜索數(shù)組中最后出現(xiàn)的下標(biāo)位置;
const fruits = ['apple', 'banana', 'kiwi', 'banana', 'orange'];
const lastIndex = fruits.lastIndexOf('banana');
console.log(lastIndex); // 3
2、從指定位置開始查找最后出現(xiàn)的下標(biāo)位置;
const numbers = [1, 2, 3, 4, 5, 3, 2, 1];
const lastIndexFromIndex = numbers.lastIndexOf(3, 4);
console.log(lastIndexFromIndex); // 2
11、forEach
功能:對數(shù)組中的每個元素執(zhí)行指定的函數(shù)
forEach() 方法通常用于對數(shù)組中的每個元素執(zhí)行操作,而不返回新數(shù)組。它提供了一種迭代數(shù)組并對每個元素執(zhí)行相同操作的便捷方法。
注意:forEach()方法不能中斷或跳過迭代,它會遍歷數(shù)組中的每個元素,即使回調(diào)函數(shù)中使用了return語句,也不會中止遍歷。
12、map
功能:對數(shù)組中的每個元素執(zhí)行指定的函數(shù),并返回由執(zhí)行結(jié)果組成的新數(shù)組。
用法示例:
map()方法可以根據(jù)自定義的處理邏輯對數(shù)組中的每個元素進(jìn)行變換。您可以使用它生成一個新數(shù)組,其元素是處理原始數(shù)組的結(jié)果。
常見的使用場景包括對數(shù)組中每個元素的計算、轉(zhuǎn)換、映射等操作。
13、filter
作用:根據(jù)指定條件過濾掉數(shù)組中符合條件的元素,返回一個新數(shù)組
用法示例:
使用filter方法,可以從數(shù)組中過濾掉滿足特定條件的元素。
14、reduce
功能:對數(shù)組中的所有元素執(zhí)行指定的歸約函數(shù),并返回單值結(jié)果
參數(shù)說明:callback是回調(diào)函數(shù),可以接受四個參數(shù):
- accumulator:累加器,用于保存計算結(jié)果。
- currentValue:當(dāng)前遍歷的元素。
- index:當(dāng)前遍歷元素的索引。
- array:正在遍歷的數(shù)組。
用法示例:
調(diào)用reduce()方法,傳入累加函數(shù)(accumulator, currentValue) => Accumulator + currentValue,累加數(shù)組中所有元素。
累加器的初始值未指定,因此,reduce() 方法從數(shù)組的第一個元素開始,將當(dāng)前元素添加到累加器,并更新累加器的值。最后返回的累加結(jié)果是數(shù)組所有元素的累加和。
15、sort
功能:對數(shù)組元素進(jìn)行排序
用法示例:
// sort()
const fruits = ['banana','apple','kiwi','pear'];
fruits.sort();
console.log(fruits);
// Output:['apple','banana','kiwi','pear']
1、不傳遞參數(shù)調(diào)用sort,會直接修改原數(shù)組,返回排序后的數(shù)組;
2、傳入比較函數(shù),該函數(shù)接受兩個參數(shù),返回一個代表比較結(jié)果的數(shù)字;
16、reverse
功能:反轉(zhuǎn)數(shù)組中元素的順序
通過使用reverse()方法,可以輕松反轉(zhuǎn)數(shù)組中元素的順序,適用于需要反轉(zhuǎn)數(shù)組內(nèi)容的情況。
注意:reverse()方法會直接修改原數(shù)組,不會創(chuàng)建新數(shù)組。如果需要保留原始數(shù)組的副本并執(zhí)行反向操作,可以先使用 slice() 方法創(chuàng)建一個新數(shù)組,然后調(diào)用reverse() 方法。
17、includes
功能:判斷數(shù)組是否包含指定元素,返回true或false
用法示例:
1. 檢查數(shù)組是否包含特定元素:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3)); // true
console.log(numbers.includes(6)); // false
2.使用fromIndex參數(shù)指定搜索的起始位置:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3, 2)); // true, search starts from index 2
console.log(numbers.includes(3, 4)); // false, search starts from index 4
3. 檢查數(shù)組中是否包含字符串:
const fruits = ['apple', 'banana', 'kiwi', 'pear'];
console.log(fruits.includes('banana')); // true
console.log(fruits.includes('grape')); // false
18、some
功能:檢查數(shù)組中是否至少有一個元素滿足指定條件,返回true或false
用法示例:
1、檢查數(shù)組中是否有大于10的元素:
const numbers = [5, 8, 12, 3, 9];
const hasGreaterThan10 = numbers.some(element => element > 10);
console.log(hasGreaterThan10); // true
2. 檢查數(shù)組中是否有偶數(shù):
const numbers = [3, 7, 5, 12, 9];
const hasEvenNumber = numbers.some(element => element % 2 === 0);
console.log(hasEvenNumber); // true
3. 檢查數(shù)組中是否存在包含特定字符的字符串:
const fruits = ['apple', 'banana', 'kiwi', 'pear'];
const hasStrWithChar = fruits.some(element => element.includes('a'));
console.log(hasStrWithChar); // true
4、檢查數(shù)組中是否存在滿足復(fù)雜條件的元素:
const students = [
{ name: 'Alice', score: 85 },
{ name: 'Bob', score: 92 },
{ name: 'Charlie', score: 76 },
];
const hasPassingScore = students.some(student => student.score >= 80);
console.log(hasPassingScore); // true
19、every
功能:檢查數(shù)組中所有元素是否滿足指定條件,返回true或false
用法示例:
1.檢查數(shù)組中的所有元素是否都大于 0:
const numbers = [5, 8, 12, 3, 9];
const allGreaterThan0 = numbers.every(element => element > 0);
console.log(allGreaterThan0); // true
2.檢查數(shù)組中的所有元素是否都是偶數(shù):
const numbers = [2, 4, 6, 8, 10];
const allEvenNumbers = numbers.every(element => element % 2 === 0);
console.log(allEvenNumbers); // true
3.檢查數(shù)組中的所有字符串是否以大寫字母開頭:
const words = ['Apple', 'Banana', 'Cherry', 'Durian'];
const allUpperCaseStart = words.every(element => /^[A-Z]/.test(element));
console.log(allUpperCaseStart); // true
4.檢查數(shù)組中的所有對象是否滿足特定條件:
const students = [
{ name: 'Alice', score: 85 },
{ name: 'Bob', score: 92 },
{ name: 'Charlie', score: 76 },
];
const allPassingScore = students.every(student => student.score >= 80);
console.log(allPassingScore); // false
總結(jié)
以上就是我今天與你分享的19個常用的Array方法, 你學(xué)會了嗎?
當(dāng)然,Array在ES6中還有一些更高級的使用方法,可以更加快速地操作Array。