JavaScript 中最常用的數(shù)組方法整理匯總

英文 | https://javascript.plainenglish.io/20-most-used-array-methods-in-javascript-c57276982377
翻譯 | 楊小愛
在 JavaScript 中,一個(gè)數(shù)組實(shí)例有 37 個(gè)內(nèi)置方法,常用的方法大約有 20 個(gè)。在這篇文章中,我對(duì)這些方法進(jìn)行了總結(jié),并附上了一些圖表,希望能幫助你更好地整理相關(guān)知識(shí)點(diǎn)。
push, pop, shift, unshift
這四種方法非常相似,我們一起來談?wù)劇?/span>
push(element) :將一個(gè)或多個(gè)元素添加到數(shù)組的末尾,并返回?cái)?shù)組的新長(zhǎng)度。
pop():從數(shù)組中刪除最后一個(gè)元素并返回該元素。
shift() :從數(shù)組中移除第一個(gè)元素并返回移除的元素。
unshift() :將一個(gè)或多個(gè)元素添加到數(shù)組的開頭并返回?cái)?shù)組的新長(zhǎng)度。


測(cè)試一下:
push:
const animals = ['pigs', 'goats', 'sheep'];const count = animals.push('cows');console.log(count);// expected output: 4console.log(animals);// expected output: Array ["pigs", "goats", "sheep", "cows"];
const myFish = ['angel', 'clown', 'mandarin', 'surgeon'];console.log('myFish before:', myFish);// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']const shifted = myFish.shift();console.log('myFish after:', myFish);// myFish after: ['clown', 'mandarin', 'surgeon']console.log('Removed this element:', shifted);// Removed this element: angel;
unshift:
const array1 = [1, 2, 3];console.log(array1.unshift(4, 5));// expected output: 5console.log(array1);// expected output: Array [4, 5, 1, 2, 3];
slice() 方法返回?cái)?shù)組一部分的淺拷貝。
它返回一個(gè)新數(shù)組,并且不會(huì)修改原始數(shù)組。

語(yǔ)法:
array.slice(startIndex, endIndex)let arr = ['a', 'b', 'c', 'd', 'e', 'f']console.log('arr.slice(1, 4) : ', arr.slice(1, 4))console.log('arr.slice(2) : ', arr.slice(2))console.log('arr.slice() : ', arr.slice());
splice() 方法通過刪除或替換現(xiàn)有元素和/或在適當(dāng)位置添加新元素來更改數(shù)組的內(nèi)容。
語(yǔ)法:
splice(start)splice(start, deleteCount)splice(start, deleteCount, item1)splice(start, deleteCount, item1, item2, itemN)
start:開始更改數(shù)組的索引。
deleteCount:一個(gè)整數(shù),指示數(shù)組中要從開始刪除的元素?cái)?shù)。
item1, item2, ...:要添加到數(shù)組中的元素,從 start 開始。


測(cè)試一下:
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']let removed = myFish.splice(2, 0, 'drum')console.log('myFish: ', myFish)console.log('removed: ', removed);
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']let removed = myFish.splice(2, 0, 'drum')console.log('myFish: ', myFish)console.log('removed: ', removed);
concat
concat() 方法用于合并兩個(gè)或多個(gè)數(shù)組。
此方法不會(huì)更改現(xiàn)有數(shù)組,而是返回一個(gè)新數(shù)組。

測(cè)試一下:
const array1 = ['a', 'b', 'c'];const array2 = ['d', 'e', 'f'];const array3 = array1.concat(array2);console.log(array3);// expected output: Array ["a", "b", "c", "d", "e", "f"];
join
join() 方法通過連接數(shù)組中的所有元素創(chuàng)建并返回一個(gè)新字符串,該數(shù)組由逗號(hào)或指定的分隔符字符串分隔。
語(yǔ)法:
join(separator)
測(cè)試一下:
let arr = ['a', 'b', 'c', 'd'];console.log(`arr.join(''): `, arr.join(''))console.log(`arr.join('-'): `, arr.join('-'))console.log(`arr.join(): `, arr.join())console.log(`arr.join('??'): `, arr.join('??'));
你可以猜一猜他們的輸出結(jié)果是多少?
every
every() 方法測(cè)試數(shù)組中的所有元素是否通過提供的函數(shù)實(shí)現(xiàn)的測(cè)試,它返回一個(gè)布爾值。

測(cè)試一下:
function isEven(num){return num % 2 === 0}console.log([2, 4, 6, 0].every(isEven))console.log([2, 5, 6, 9].every(isEven))console.log([2, 4, 7, 0].every(isEven));
some
some() 方法測(cè)試數(shù)組中的至少一個(gè)元素是否通過了提供的函數(shù)實(shí)現(xiàn)的測(cè)試。
如果在數(shù)組中找到所提供函數(shù)為其返回 true 的元素,則返回 true;
否則,它返回 false。

它不會(huì)修改數(shù)組。
測(cè)試一下:
function isEven(num){return num % 2 === 0}console.log([2, 4, 6, 1].some(isEven))console.log([1, 5, 7, 9].some(isEven))console.log([2, 4, 7, 0].some(isEven));
map
map() 方法創(chuàng)建一個(gè)新數(shù)組,其中填充了在調(diào)用數(shù)組中的每個(gè)元素上調(diào)用提供的函數(shù)的結(jié)果。
語(yǔ)法:
// Arrow functionmap((element) => { /* ... */ })map((element, index) => { /* ... */ })map((element, index, array) => { /* ... */ })// Callback functionmap(callbackFn)map(callbackFn, thisArg)
測(cè)試一下
const double = ele => ele * 2let arr = [1, 2, 3, 4, 5]console.log(arr.map(double));
reduce
reduce() 方法按順序?qū)?shù)組的每個(gè)元素執(zhí)行用戶提供的“reducer”回調(diào)函數(shù),傳入前一個(gè)元素的計(jì)算返回值。在數(shù)組的所有元素上運(yùn)行 reducer 的最終結(jié)果是單個(gè)值。
reduce((previousValue, currentValue) => { /* ... */ } )我知道上面抽象的概念不好理解,我們來看一個(gè)例子。
var arr = ['a', 'b', 'c', 'd', 'e'];function add(x, y) {return x + y;}arr.reduce(add)
這段代碼是如何執(zhí)行的?
在這段代碼中,reducer 是 add 。
首先,因?yàn)槲覀兪堑谝淮螆?zhí)行add,所以數(shù)組中的第一個(gè)元素'a'會(huì)被當(dāng)作add的第一個(gè)參數(shù),然后循環(huán)會(huì)從數(shù)組的第二個(gè)元素'b'開始。這一次,'b' 是 add 的第二個(gè)參數(shù)。




var arr = ['a', 'b', 'c', 'd', 'e'];function add(x, y) {return x + y;}arr.reduce(add);
filter
filter() 方法創(chuàng)建一個(gè)新數(shù)組,其中包含通過所提供函數(shù)實(shí)現(xiàn)的測(cè)試的所有元素。

測(cè)試一下
function isEven(num){return num % 2 === 0}let arr = [1, 2, 3, 4, 5, 6]console.log(arr.filter(isEven))console.log(arr.filter(ele => ele > 100));
fill
fill() 方法將數(shù)組中的所有元素更改為靜態(tài)值,從開始索引(默認(rèn) 0)到結(jié)束索引(默認(rèn) array.length)。它返回修改后的數(shù)組。
語(yǔ)法:
fill(value)fill(value, start)fill(value, start, end)

find() :返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)的第一個(gè)元素的值,如果沒有找到合適的元素,則返回 undefined。
findIndex() :返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)的第一個(gè)元素的索引,如果沒有找到合適的元素,則返回 -1。
findLast() :返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)的最后一個(gè)元素的值,如果沒有找到合適的元素,則返回 undefined。
findLastIndex() :返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)的最后一個(gè)元素的索引,如果沒有找到合適的元素,則返回 -1。

let arr = [2, 'a', 7, 0, 'a', 0]const isString = ele => typeof ele === 'string'console.log(arr.find(isString))console.log(arr.findIndex(isString))console.log(arr.findLast(isString))console.log(arr.findLastIndex(isString));
總結(jié)
以上就是我今天跟你分享的關(guān)于JavaScript常用數(shù)組的總結(jié),如果你覺得有用的話,請(qǐng)記得點(diǎn)贊我,關(guān)注我,并將它分享給你身邊做開發(fā)的朋友,也許能夠幫助到他。
最后,感謝你的閱讀,祝編程愉快!
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

