12種JavaScript中最常用的數(shù)組操作整理匯總

來(lái)源 | https://www.fly63.com/
數(shù)組是最常見的數(shù)據(jù)結(jié)構(gòu)之一,我們需要絕對(duì)自信地使用它。在這里,我將列出 JavaScript 中最重要的幾個(gè)數(shù)組常用操作片段,包括數(shù)組長(zhǎng)度、替換元素、去重以及許多其他內(nèi)容。
1、數(shù)組長(zhǎng)度
大多數(shù)人都知道可以像這樣得到數(shù)組的長(zhǎng)度:
const arr = [1, 2, 3];console.log(arr.length); // 3
有趣的是,我們可以手動(dòng)修改長(zhǎng)度。這就是我所說(shuō)的:
const arr = [1, 2, 3];arr.length = 2;arr.forEach(i => console.log(i)); // 1 2
甚至創(chuàng)建指定長(zhǎng)度的新數(shù)組:
const arr = [];arr.length = 100;console.log(arr) // [undefined, undefined, undefined ...]
這不是一個(gè)很好的實(shí)踐,但是值得了解。
我們常常需要清空數(shù)組時(shí)候會(huì)使用:
const arr = [1, 2];arr.length = 0;console.log(arr) // []
如果 arr 的值是共享的,并且所有參與者都必須看到清除的效果,那么這就是你需要采取的方法。
但是,JavaScript 語(yǔ)義規(guī)定,如果減少數(shù)組的長(zhǎng)度,則必須刪除新長(zhǎng)度及以上的所有元素。
而且這需要花費(fèi)時(shí)間(除非引擎對(duì)設(shè)置長(zhǎng)度為零的特殊情況進(jìn)行了優(yōu)化)。實(shí)際上,一個(gè)性能測(cè)試表明,在所有當(dāng)前的 JavaScript 引擎上,這種清除方法更快。
2、替換數(shù)組元素
有幾種方法可以解決這個(gè)問題。如果需要替換指定索引處的元素,請(qǐng)使用 splice:
const arr = [1, 2, 3];arr.splice(2, 1, 4); // 將索引 2 開始的 1 元素更改為 4console.log(arr); // [1, 2, 4]arr.splice(0, 2, 5, 6) // 將索引 0 開始的 2 個(gè)元素更改為 5 和 6console.log(arr); // [5, 6, 4]
splice 在數(shù)組刪除有更多的說(shuō)明
如果你需要根據(jù)項(xiàng)目的內(nèi)容替換項(xiàng)目,或者必須創(chuàng)建一個(gè)新數(shù)組,請(qǐng)使用 map:
const arr = [1, 2, 3, 4, 5, 6];// 所有奇數(shù)的平方const arr2 = arr.map(item => item % 2 == 0 ? item : item*item);console.log(arr2); // [1, 2, 9, 4, 25, 6];
map 接受函數(shù)作為其參數(shù)。它將對(duì)數(shù)組中的每個(gè)元素調(diào)用該函數(shù)一次,并生成一個(gè)新的函數(shù)返回的項(xiàng)數(shù)組。
關(guān)于 map 有個(gè)經(jīng)典的面試題:['1', '2', '3', '4', '5'].map(parseInt) => ?
3、過(guò)濾數(shù)組
在某些情況下,你需要?jiǎng)h除數(shù)組中的某些元素,然后創(chuàng)建一個(gè)新的元素。在這種情況下,使用在ES5中引入的很棒的 filter 方法:
const arr = [1, 2, 3, 4, 5, 6, 7];// 過(guò)濾掉所有奇數(shù)const arr2 = arr.filter(item => item % 2 == 0);console.log(arr2); // [2, 4, 6];
filter 的工作原理與 map 非常相似。向它提供一個(gè)函數(shù),filter 將在數(shù)組的每個(gè)元素上調(diào)用它。如果要在新數(shù)組中包含此特定元素,則函數(shù)必須返回 true,否則返回 false。
4、 合并數(shù)組
如果你想將多個(gè)數(shù)組合并為一個(gè)數(shù)組,有兩種方法。
Array 提供了 concat 方法:
const arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const arr3 = arr1.concat(arr2);console.log(arr3 ); // [1, 2, 3, 4, 5, 6]
ES6 中引入了 spread operator,一種更方便的方法:
const arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const arr3 = [...arr1, ...arr2];console.log(arr3 ); // [1, 2, 3, 4, 5, 6]
還有一種比較奇特方法:
const arr1 = [1, 2, 3];const arr2 = [4, 5, 6];Array.prototype.push.apply(arr1, arr2);console.log(arr1); // [1, 2, 3, 4, 5, 6]
上面 2 種通用的方法,都不會(huì)改變?cè)瓟?shù)組,最后一種奇特方法,會(huì)改變 push 的原數(shù)組,謹(jǐn)慎使用。
Array.prototype.push.apply 和 concat 對(duì)比:
數(shù)據(jù)上萬(wàn)情況下,兩者性能相差毫秒個(gè)位數(shù)級(jí)別
Array.prototype.push.apply 數(shù)組長(zhǎng)度有限制,不同瀏覽器不同,一般不能超過(guò)十萬(wàn), concat 無(wú)限制
Array.prototype.push.apply 會(huì)改變?cè)瓟?shù)組, concat 不會(huì)
正常情況下我們都應(yīng)該使用 concat 和 spread operator,有種情況下可以使用,如果頻繁合并數(shù)組可以用 Array.prototype.push.apply。
5、復(fù)制數(shù)組
總所周知,定義數(shù)組變量存儲(chǔ)不是數(shù)組值,而只是存儲(chǔ)引用。 這是我的意思:
const arr1 = [1, 2, 3];const arr2 = arr1;arr2[0] = 4;arr2[1] = 2;arr2[2] = 0;console.log(arr1); // [4, 2, 0]
因?yàn)?arr2 持有對(duì) arr1 的引用,所以對(duì) arr2 的任何更改都是對(duì) arr1 的更改。
const arr1 = [1, 2, 3];const arr2 = arr1.slice(0);arr2[0] = 4;arr2[1] = 2;arr2[2] = 0;console.log(arr1); // [1, 2, 3]console.log(arr2); // [4, 2, 0]
我們也可以使用 ES6 的 spread operator:
const arr1 = [1, 2, 3];const arr2 = [...arr1];arr2[0] = 4;arr2[1] = 2;arr2[2] = 0;console.log(arr1); // [1, 2, 3]console.log(arr2); // [4, 2, 0]
也可以使用前面合并使用的 concat 方法
const arr1 = [1, 2, 3];const arr2 = [].concat(arr1);arr2[0] = 4;arr2[1] = 2;arr2[2] = 0;console.log(arr1); // [1, 2, 3]console.log(arr2); // [4, 2, 0]
注意:如果想要了解更多的數(shù)組復(fù)制,請(qǐng)查詢 數(shù)組深拷貝和淺拷貝 相關(guān)資料,這里只實(shí)現(xiàn)了淺拷貝。
6、數(shù)組去重
數(shù)組去重是面試經(jīng)常問的,數(shù)組去重方式很多,這里介紹比較簡(jiǎn)單直白的三種方法:
可以使用 filter 方法幫助我們刪除重復(fù)數(shù)組元素。filter 將接受一個(gè)函數(shù)并傳遞 3 個(gè)參數(shù):當(dāng)前項(xiàng)、索引和當(dāng)前數(shù)組。
const arr1 = [1, 1, 2, 3, 1, 5, 9, 4, 2];const arr2 = arr1.filter((item, index, arr) => arr.indexOf(item) == index);console.log(arr2); // [1, 2, 3, 5, 9, 4]
可以使用 reduce 方法從數(shù)組中刪除所有重復(fù)項(xiàng)。然而,這有點(diǎn)棘手。reduce 將接受一個(gè)函數(shù)并傳遞 2 個(gè)參數(shù):數(shù)組的當(dāng)前值和累加器。
累加器在項(xiàng)目之間保持相同,并最終返回:
const arr1 = [1, 1, 2, 3, 1, 5, 9, 4, 2];const arr2 = arr1.reduce((acc, item) => acc.indexOf(item) == -1 ? [...acc, item]: acc,[] // 初始化當(dāng)前值);console.log(arr2); // [1, 2, 3, 5, 9, 4]
可以使用 ES6 中引入的新數(shù)據(jù)結(jié)構(gòu) set 和 spread operator:
const arr1 = [1, 1, 2, 3, 1, 5, 9, 4, 2];const arr2 = [...(new Set(arr1))];console.log(arr2); // [1, 2, 3, 5, 9, 4]
還有很多其他去重方式,比如使用 {} + for。
7、轉(zhuǎn)換為數(shù)組
有時(shí)我們必須將一些其它數(shù)據(jù)結(jié)構(gòu),如集合或字符串轉(zhuǎn)換為數(shù)組。
類數(shù)組:函數(shù)參數(shù),dom 集合
Array.prototype.slice.call(arguments);Array.prototype.concat.apply([], arguments);
字符串:
console.log('string'.split('')); // ["s", "t", "r", "i", "n", "g"]console.log(Array.from('string')); // ["s", "t", "r", "i", "n", "g"]
集合:
console.log(Array.from(new Set(1,2,3))); // [1,2,3]console.log([...(new Set(1,2,3))]); // [1,2,3]
8、數(shù)組遍歷
數(shù)組遍歷方式很多,有底層的,有高階函數(shù)式,我們就來(lái)介紹幾種:
for:
const arr = [1, 2, 3];for (let i = 0; i < arr.length; i++) {console.log(arr[i]);}// 1 2 3
for-in:
const arr = [1, 2, 3];for (let i in arr) {if(arr.hasOwnProperty(i)) {console.log(arr[i]);}}// 1 2 3
for-of:
const arr = [1, 2, 3];for (let i of arr) {console.log(i);}// 1 2 3
forEach:
[1, 2, 3].forEach(i => console.log(i))// 1 2 3
while:
const arr = [1,2,3];let i = -1;const length = arr.length;while(++i < length) {console.log(arr[i])}// 1 2 3
迭代輔助語(yǔ)句:break 和 continue
break 語(yǔ)句是跳出當(dāng)前循環(huán),并執(zhí)行當(dāng)前循環(huán)之后的語(yǔ)句
continue 語(yǔ)句是終止當(dāng)前循環(huán),并繼續(xù)執(zhí)行下一次循環(huán)
上面方式中,除了 forEach 不支持跳出循環(huán)體,其他都支持。高階函數(shù)式方式都類似 forEach 。
性能對(duì)比:
while > for > for-of > forEach > for-in
如果是編寫一些庫(kù)或者大量數(shù)據(jù)遍歷,推薦使用 while。有名的工具庫(kù) lodash 里面遍歷全是 while。正常操作,for-of 或者 forEach 已經(jīng)完全滿足需求。
下面介紹幾種高級(jí)函數(shù)式,滿足條件為 true 立即終止循環(huán),否則繼續(xù)遍歷到整個(gè)數(shù)組完成的方法:
// ES5[1, 2, 3].some((i) => i == 1);// ES6[1, 2, 3].find((i) => i == 1);[1, 2, 3].findIndex((i) => i == 1);
其他高階函數(shù)式方法,例如 forEach map filter reduce reduceRight every sort 等,都是把整個(gè)數(shù)組遍歷。
9、扁平化多維數(shù)組
這個(gè)功能說(shuō)不是很常用,但是有時(shí)候又會(huì)用到:
二維數(shù)組:
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];const arr2 = [].concat.apply([], arr1);console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
三維數(shù)組:
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]];const arr2 = [].concat.apply([], arr1);console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9, [1, 2, 3], [4, 5, 6], [7, 8, 9]]
concat.apply 方式只能扁平化二維數(shù)組,在多了就需要遞歸操作。
function flatten(arr) {return arr.reduce((flat, toFlatten) => {return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);}, []);}const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]];const arr2 = flatten(arr1);console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ES6+(ES2019) 給我們提供一個(gè) flat 方法:
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];const arr2 = arr1.flat();console.log(arr2); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
默認(rèn)只是扁平化二維數(shù)組,如果想要扁平化多維,它接受一個(gè)參數(shù) depth,如果想要展開無(wú)限的深度使用 Infinity:
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]];const arr2 = arr1.flat(Infinity);console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
還有一種面試扁平化二維數(shù)組方式:
const arr1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]];const arr2 = arr1.toString().split(',').map(n => parseInt(n, 10));console.log(arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
10、數(shù)組添加
如何從數(shù)組中添加元素?
我們可以使用 push 從數(shù)組末尾添加元素,使用 unshift 從開頭添加元素,或者使用 splice 從中間添加元素。concat 方法可創(chuàng)建帶有所需項(xiàng)目的新數(shù)組,這是一種添加元素的更高級(jí)的方法。
從數(shù)組的末尾添加元素:
const arr = [1, 2, 3, 4, 5, 6];arr.push(7)console.log( arr ); // [1, 2, 3, 4, 5, 6, 7]
從數(shù)組的開頭添加元素:
const arr = [1, 2, 3, 4, 5, 6];arr.unshift(0)console.log( arr ); // [0, 1, 2, 3, 4, 5, 6]
push 方法的工作原理與 unshift 方法非常相似,方法都沒有參數(shù),都是返回?cái)?shù)組更新的 length 屬性。它修改調(diào)用它的數(shù)組。
使用 splice 添加數(shù)組元素:
只需要把 splice,第二個(gè)參數(shù)設(shè)為 0 即可,splice 在數(shù)組刪除有更多的說(shuō)明
const arr = [1, 2, 3, 4, 5];arr.splice(1, 0, 10)console.log(arr); // [1, 10, 2, 3, 4, 5]
使用 concat 添加數(shù)組元素:
const arr1 = [1, 2, 3, 4, 5];const arr2 = arr1.concat(6);console.log(arr2); // [1, 2, 3, 4, 5, 6]
11、數(shù)組刪除
數(shù)組允許我們對(duì)值進(jìn)行分組并對(duì)其進(jìn)行遍歷。 我們可以通過(guò)不同的方式添加和刪除數(shù)組元素。 不幸的是,沒有簡(jiǎn)單的 Array.remove 方法。
那么,如何從數(shù)組中刪除元素?
除了 delete 方式外,JavaScript 數(shù)組還提供了多種清除數(shù)組值的方法。
我們可以使用 pop 從數(shù)組末尾刪除元素,使用 shift 從開頭刪除元素,或者使用 splice 從中間刪除元素。
filter 方法可創(chuàng)建帶有所需項(xiàng)目的新數(shù)組,這是一種刪除不需要的元素的更高級(jí)的方法。
從數(shù)組的末尾刪除元素:
通過(guò)將 length 屬性設(shè)置為小于當(dāng)前數(shù)組長(zhǎng)度,可以從數(shù)組末尾刪除數(shù)組元素。 索引大于或等于新長(zhǎng)度的任何元素都將被刪除。
const arr = [1, 2, 3, 4, 5, 6];arr.length = 4;console.log( arr ); // [1, 2, 3, 4]
pop 方法刪除數(shù)組的最后一個(gè)元素,返回該元素,并更新length屬性。pop 方法會(huì)修改調(diào)用它的數(shù)組,這意味著與使用 delete 不同,最后一個(gè)元素被完全刪除并且數(shù)組長(zhǎng)度減小。
const arr = [1, 2, 3, 4, 5, 6];arr.pop();console.log( arr ); // [1, 2, 3, 4, 5]
從數(shù)組的開頭刪除元素:
shift 方法的工作原理與 pop 方法非常相似,只是它刪除了數(shù)組的第一個(gè)元素而不是最后一個(gè)元素。
const arr = [1, 2, 3, 4, 5, 6];arr.shift();console.log( arr ); // [2, 3, 4, 5, 6]
shift 和 pop 方法都沒有參數(shù),都是返回已刪除的元素,更新剩余元素的索引,并更新 length 屬性。它修改調(diào)用它的數(shù)組。如果沒有元素,或者數(shù)組長(zhǎng)度為 0,該方法返回 undefined。
使用 splice 刪除數(shù)組元素:
splice 方法可用于從數(shù)組中添加、替換或刪除元素。
splice 方法接收至少三個(gè)參數(shù):
start:在數(shù)組中開始刪除元素的位置
deleteCount:刪除多少個(gè)元素(可選)
items...:添加元素(可選)
splice 可以實(shí)現(xiàn)添加、替換或刪除。
刪除:
如果 deleteCount 大于 start 之后的元素的總數(shù),則從 start 后面的元素都將被刪除(含第 start 位)。
如果 deleteCount 被省略了,或者它的值大于等于array.length - start(也就是說(shuō),如果它大于或者等于start之后的所有元素的數(shù)量),那么start之后數(shù)組的所有元素都會(huì)被刪除。
如果 deleteCount 是 0 或者負(fù)數(shù),則不移除元素。這種情況下,至少應(yīng)添加一個(gè)新元素。
const arr1 = [1, 2, 3, 4, 5];arr1.splice(1);console.log(arr1); // [1];const arr2 = [1, 2, 3, 4, 5];arr2.splice(1, 2)console.log(arr2); // [1, 4, 5]const arr3 = [1, 2, 3, 4, 5];arr3.splice(1, 1)console.log(arr3); // [1,3, 4, 5]
添加:
添加只需要把 deleteCount 設(shè)置為 0,items 就是要添加的元素。
const arr = [1, 2, 3, 4, 5];arr.splice(1, 0, 10)console.log(arr); // [1, 10, 2, 3, 4, 5]
替換:
添加只需要把 deleteCount 設(shè)置為和 items 個(gè)數(shù)一樣即可,items 就是要添加的元素。
const arr = [1, 2, 3, 4, 5];arr.splice(1, 1, 10)console.log(arr); // [1, 10, 3, 4, 5]
注意:splice 方法實(shí)際上返回兩個(gè)數(shù)組,即原始數(shù)組(現(xiàn)在缺少已刪除的元素)和僅包含已刪除的元素的數(shù)組。如果循環(huán)刪除元素或者多個(gè)相同元素,最好使用倒序遍歷。
使用 delete 刪除單個(gè)數(shù)組元素:
使用 delete 運(yùn)算符不會(huì)影響 length 屬性。它也不會(huì)影響后續(xù)數(shù)組元素的索引。數(shù)組變得稀疏,這是說(shuō)刪除的項(xiàng)目沒有被刪除而是變成 undefined 的一種奇特的方式。
const arr = [1, 2, 3, 4, 5];delete arr[1]console.log(arr); // [1, empty, 3, 4, 5]
實(shí)際上沒有將元素從數(shù)組中刪除的原因是 delete 運(yùn)算符更多的是釋放內(nèi)存,而不是刪除元素。 當(dāng)不再有對(duì)該值的引用時(shí),將釋放內(nèi)存。
使用數(shù)組 filter 方法刪除匹配的元素:
與 splice 方法不同,filter 創(chuàng)建一個(gè)新數(shù)組。
filter 接收一個(gè)回調(diào)方法,回調(diào)返回 true 或 false。返回 true 的元素被添加到新的經(jīng)過(guò)篩選的數(shù)組中。
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];const filtered = arr.filter((value, index, arr) => value > 5);console.log(filtered); // [6, 7, 8, 9]console.log(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
清除或重置數(shù)組:
最簡(jiǎn)單和最快的技術(shù)是將數(shù)組變量設(shè)置為空數(shù)組
let arr = [1,2,3];arr = [];
清除數(shù)組的一個(gè)簡(jiǎn)單技巧是將其 length 屬性設(shè)置為 0。
let arr = [1,2,3];arr.length = 0;
使用 splice 方法,不傳遞第二個(gè)參數(shù)。這將返回原始元素的一個(gè)副本,這對(duì)于我們的有些場(chǎng)景可能很方便。也是一種數(shù)組復(fù)制方法技巧。
let arr = [1,2,3];arr.splice(0);
使用 while 循環(huán),這不是一種常用清除數(shù)組的方法,但它確實(shí)有效,而且可讀性強(qiáng)。一些性能測(cè)試也顯示這是最快的技術(shù)。
const arr = [1, 2, 3, 4, 5, 6];while (arr.length) { arr.pop(); }console.log(arr); // []
12、其他方法
剔除假值:
[1, false, '', NaN, 0, [], {}, '123'].filter(Boolean) // [1, [], {}, '123']
是否有一個(gè)真值:
[1, false, '', NaN, 0, [], {}, '123'].some(Boolean) // true
是否全部都是真值:
[1, false, '', NaN, 0, [], {}, '123'].every(Boolean) // false
補(bǔ)零:
Array(6).join('0'); // '00000' 注意:如果要補(bǔ)5個(gè)0,要寫6,而不是5。Array(5).fill('0').join('') // '00000'
數(shù)組最大值和最小值:
Math.max.apply(null, [1, 2, 3, 4, 5]) // 5Math.min.apply(null, [1, 2, 3, 4, 5]) // 1
判斷回文字符串:
const str1 = 'string';const str2 = str1.split('').reverse().join('');console.log(str1 === str2); // false
數(shù)組模擬隊(duì)列:
隊(duì)列先進(jìn)先出:
const arr = [1];// 入隊(duì)arr.push(2);console.log('入隊(duì)元素:', arr[arr.length -1]); // 2// 出隊(duì)console.log('出隊(duì)元素:', arr.shift()); // 1
獲取數(shù)組最后一個(gè)元素:
像我們平常都是這樣來(lái)獲取:
const arr = [1, 2, 3, 4, 5];console.log(arr[arr.length - 1]); // 5
感覺很麻煩,不過(guò) ES 有了提案,未來(lái)可以通過(guò) arr[-1] 這種方式來(lái)獲取,Python 也有這種風(fēng)騷的操作:
目前我們可以借助 ES6 的 Proxy 對(duì)象來(lái)實(shí)現(xiàn):
const arr1 = [1, 2, 3, 4, 5];function createNegativeArrayProxy(array) {if (!Array.isArray(array)) {throw new TypeError('Expected an array');}return new Proxy(array, {get: (target, prop, receiver) => {prop = +prop;return Reflect.get(target, prop < 0 ? target.length + prop : prop, receiver);;}})}const arr2 = createNegativeArrayProxy(arr1);console.log(arr1[-1]) // undefinedconsole.log(arr1[-2]) // undefinedconsole.log(arr2[-1]) // 5console.log(arr2[-2]) // 4
注意:這樣方式雖然有趣,但是會(huì)引起性能問題,50萬(wàn)次循環(huán)下,在Chrome瀏覽器,代理數(shù)組的執(zhí)行時(shí)間大約為正常數(shù)組的50倍,在Firefox瀏覽器大約為20倍。在大量循環(huán)情況下,請(qǐng)慎用。無(wú)論是面試還是學(xué)習(xí),你都應(yīng)該掌握 Proxy 用法。
本文完~
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

