JavaScript 中 15 種常見的數組操做

做者:Dmitri Pavlutin
譯者:前端小智
來源:dmitripavlutin.com
點贊再看,養成習慣

本文 GitHub https://github.com/qq44924588... 上已經收錄,更多往期高贊文章的分類,也整理了不少個人文檔,和教程資料。歡迎Star和完善,你們面試能夠參照考點複習,但願咱們一塊兒有點東西。javascript

數組是 JS 中普遍使用的數據結構。數組對象提供了大量有用的方法,如array. forEach()array.map()等來操做數組。前端

在實戰中,我常常對數組可能的操做和相應採用哪一個更好的方法不知所措,因此本文就列出 15 種經常使用數據方法,讓我們重溫增強記憶一下。java

1. 數組的遍歷

1.1 for..of 循環

for(const item of items)循環遍歷數組項,以下所示遍歷colors列表:git

const colors = ['blue', 'green', 'white'];

for (const color of colors) {
  console.log(color);
}
// 'blue'
// 'green'
// 'white'

提示:github

我們能夠隨時使用break語句中止遍歷。面試

1.2 for 循環

for(let i; i < array.length; i++)循環使用遞增的索引變量遍歷數組項。數組

for一般須要在每一個循環中遞增index 變量微信

const colors = ['blue', 'green', 'white'];

for (let index = 0; index < colors.length; index++) {
  const color = colors[index];
  console.log(color);
}
// 'blue'
// 'green'
// 'white'

index變量從0遞增到colors.length-1。此變量用於按如下索引訪問項:colors [index]數據結構

提示函數

我們能夠隨時使用break語句中止遍歷。

1.3 array.forEach() 方法

array.forEach(callback)方法經過在每一個數組項上調用callback函數來遍歷數組項。

在每次遍歷中,都使用如下參數調用callback(item [, index [, array]]):當前遍歷項,當前遍歷索引和數組自己。

const colors = ['blue', 'green', 'white'];

colors.forEach(function callback(value, index) {
  console.log(value, index);
});
// 'blue', 0
// 'green', 1
// 'white', 2

提示:

我們不能中斷array.forEach()迭代。

2. 數組的映射

2.1 Array.map()方法

array.map(callback) 方法經過在每一個數組項上使用callback調用結果來建立一個新數組。

在每一個遍歷中的callback(item[, index[, array]])使用參數調用:當前項、索引和數組自己,並應該返回新項。

以下所示我們對每一個數組元素都遞增 1

const numbers = [0, 2, 4];

const newNumbers = numbers.map(function increment(number) {
  return number + 1;
});

newNumbers; // => [1, 3, 5]

提示:

array.map()建立一個新的映射數組,而不改變原始數組。

2.2 Array.from()方法

Array.from(arrayLike[, callback])方法經過在每一個數組項上使用callback 調用結果來建立一個新數組。

在每一個遍歷中callback(item[, index[, array]])使用參數調用:當前項、索引和數組自己而且應該返回新項。

以下所示我們對每一個數組元素都遞增 1

const numbers = [0, 2, 4];

const newNumbers = Array.from(numbers,
  function increment(number) {
    return number + 1;
  }
);

newNumbers; // => [1, 3, 5]

提示:

  • Array.from()建立一個新的映射數組,而不改變原始數組。
  • Array.from()更適合從相似數組的對象進行映射。

3. 數據的簡化

3.1 Array.reduce() 方法

array.reduce(callback[, initialValue])經過調用callback 函數來將數組簡化爲一個值。

在每次遍歷中的callback(accumulator, item[, index[, array]])使用用參數調用的:累加器,當前項,索引和數組自己且應該返回累加器。

經典示例是對數字數組求和:

const numbers = [2, 0, 4];

function summarize(accumulator, number) {
  return accumulator + number;
}

const sum = numbers.reduce(summarize, 0);

sum; // => 6

第一步,將accumulator 初始化爲0。而後,對每一個累加數字和的數組項調用summary函數。

提示:

若是沒有使用 initialValue 來設置初始值,則默認使用數組的第一個元素做爲初始值。

4. 數據的鏈接

4.1 array.concat() 方法

array.concat(array1[, array2, ...])將一個或多個數組鏈接到原始數組。以下所示,鏈接兩個數組:

const heroes = ['小智', '前端小智'];
const villains = ['老王', '小三'];

const everyone = heroes.concat(villains);

everyone // ["小智", "前端小智", "老王", "小三"]

提示:

  • concat()建立一個新的數組,而不改變原來的數組
  • array.concat(array1 [,array2,...]) 接受多個要鏈接的數組。

4.2 展開操做符號

我們將展開操做符與數組字面量一塊兒使用來鏈接數組:[...array1, ...array2]

const heroes = ['小智', '前端小智'];
const villains = ['老王', '小三'];

const names = [...heroes, ...villains];

names; // ["小智", "前端小智", "老王", "小三"]

提示:

[...arr1, ...arr2, ...arrN]:我們可使用展開運算符鏈接所需數量的數組。

獲取數組的片斷

5.1 array.slice() 方法

array.slice([fromIndex [,toIndex]])返回數組的一個片斷,該片斷從fromIndex開始,以toIndex結尾(不包括toIndex自己)。fromIndex可選參數默認爲0toIndex可選參數默認爲array.length

const names = ["小智", "前端小智", "老王", "小三"]

const heroes = names.slice(0, 2)
const villains = names.splice(2)

heroes // ["小智", "前端小智"]
villains // ["老王", "小三"]

提示:

array.slice() 建立一個新數組,而不改變原始數組。

6. 數組的拷貝

6.1 展開操做符

拷貝數組的一種簡單方法是使用展開運算符:const clone = [... array],以下所示,拷貝 colors 數組:

const colors = ['white', 'black', 'gray'];

const clone = [...colors];

clone; // => ['white', 'black', 'gray']
colors === clone; // => false

提示:

[...array] 建立一個淺拷貝。

6.2 array.concat()方法

[].concat(array)是另外一種拷貝數組的方法。

const colors = ['white', 'black', 'gray'];

const clone = [].concat(colors);

clone; // => ['white', 'black', 'gray']
colors === clone; // => false

提示:

[].concat(array) 建立一個淺拷貝。

6.3 array.slice() 方法

array.slice())是另外一種拷貝數組的方法。

const colors = ['white', 'black', 'gray'];

const clone = colors.slice();

clone; // => ['white', 'black', 'gray']
colors === clone; // => false

提示:

colors.slice() 建立一個淺拷貝。

7. 查找數組

7.1 array.includes() 方法

array.includes(itemToSearch [,fromIndex])返回一個布爾值,array 是否包含itemToSearch。 可選參數fromIndex,默認爲0,表示開始搜索的索引。以下所示:判斷299是否存在於一組數字中:

const numbers = [1, 2, 3, 4, 5];

numbers.includes(2);  // => true
numbers.includes(99); // => false

7.2 array.find() 方法

array.find(predicate) 方法返回數組中知足提供的測試函數的第一個元素的值。不然返回 undefined

以下所示,找到數組中的第一個偶數:

const numbers = [1, 2, 3, 4, 5];

function isEven(number) {
  return number % 2 === 0;
}

const evenNumber = numbers.find(isEven);

evenNumber; // => 2

7.3 array.indexOf() 方法

array.indexOf(itemToSearch[, fromIndex]) 返回array中第一個出現的itemToSearch的索引。默認爲0的可選參數fromIndex表示開始搜索的索引。

以下所示,找到前端小智的索引:

const names = ["小智", "前端小智", "老王", "小三"]

const index = names.indexOf('前端小智')

index // 1

提示:

  • 若是找不到該項,則array.indexOf(itemToSearch)返回-1
  • array.findIndex(predicate)是使用predicate函數查找索引的替代方法。

8. 查詢數組

8.1 array.every() 方法

若是每一個項都經過predicate 檢查,則array.every(predicate)返回true

在每一個遍歷predicate(item[, index[, array]])上,用參數調用predicate 函數:當前遍歷項、索引和數組自己。

以下所示,肯定數組是否只包含偶數:

const evens = [0, 2, 4, 6];
const numbers = [0, 1, 4, 6];

function isEven(number) {
  return number % 2 === 0;
}

evens.every(isEven); // => true
numbers.every(isEven); // => false

8.2 array.some() 方法

若是每一個項只要一下經過predicate 檢查,則array.every(predicate)返回true

在每一個遍歷predicate(item[, index[, array]])上,用參數調用predicate 函數:當前遍歷項、索引和數組自己。

以下所示:肯定數組是否至少包含一個偶數:

const numbers = [1, 5, 7, 10];
const odds = [1, 3, 3, 3];

function isEven(number) {
  return number % 2 === 0;
}

numbers.some(isEven); // => true
odds.some(isEven);   // => false

9. 數組的過濾

9.1 array.filter() 方法

array.filter(predicate)方法建立一個新數組, 其包含經過所提供函數實現的測試的全部元素。

在每一個遍歷predicate(item[, index[, array]])上,用參數調用predicate 函數:當前遍歷項、索引和數組自己。

以下所示:將一個數組過濾爲僅包含偶數:

const numbers = [1, 5, 7, 10];

function isEven(number) {
  return number % 2 === 0;
}

const evens = numbers.filter(isEven);

evens; // => [10]

提示:

array.filter() 建立一個新數組,而不改變原始數組。

10. 數組的插入

10.1 array.push() 方法

array.push(item1 [...,itemN]) 方法將一個或多個項追加到數組的末尾,並返回新的長度。

以下所示,在names 數組的末尾添加 '小智'

const names = ['小智']

names.push('前端小智')

names // ["小智", "前端小智"]

提示:

  • array.push() 會改變原數組
  • array.push(item1, item2, ..., itemN) 能夠添加多個元素。

10.2 array.unshift() 方法

array.unshift(item1[..., itemN])方法將一個或多個項追加到數組的開頭,返回數組的新長度

const names = ['小智']

names.unshift('前端小智')

names // ["前端小智", "小智"]

提示:

  • array.unshift() 會改變原數組
  • array.unshift(item1, item2, ..., itemN) 能夠添加多個元素。

10.3 展開操做符

能夠經過組合展開操做符和數組字面量以不可變的方式在數組中插入項。

在數組末尾追加一個項:

const names = ['小智', '大治']

const names2 = [...names, '王大冶']

names2 // ["小智", "大治", "王大冶"]

在數組的開頭追加一個項:

const names = ['小智', '大治']

const names2 = [
  '王大冶',
  ...names
]

names2 // ["王大冶", "小智", "大治"]

在任何索引處插入元素:

const names = ['小智', '大治']
const indexToInsert = 1

const names2 = [
  ...names.slice(0, indexToInsert),
  '前端小智',
  ...names.slice(indexToInsert)
]

names2  // ["小智", "前端小智", "大治"]

11. 刪除數組元素

11.1 array.pop() 方法

array.pop()方法從數組中刪除最後一個元素,而後返回該元素。以下所示,刪除colors數組的最後一個元素:

const colors = ['blue', 'green', 'black'];

const lastColor = colors.pop();

lastColor; // => 'black'
colors; // => ['blue', 'green']

提示:

array.pop() 會改變原數組。

11.2 array.shift() 方法

array.shift()方法從數組中刪除第一個元素,而後返回該元素。

const colors = ['blue', 'green', 'black'];

const firstColor = colors.shift();

firstColor; // => 'blue'
colors; // => ['green', 'black']

提示:

  • array.shift() 會改變原數組。
  • array.shift()有O(n)複雜度。

11.3 array.splice() 方法

array.splice(fromIndex[, removeCount[, item1[, item2[, ...]]]])從數組中刪除元素,並插入新的元素。

例如,我們從索引1處刪除2個元素:

const names = ['張三', '李四', '王五', '趙六']

names.splice(1, 2)

names // => ["張三", "趙六"]

names.splice(1,2)刪除元素'張三''趙六'

names.splice() 能夠插入新元素,而不是插入已刪除的元素。 我們能夠替換索引1處開始的的2個元素,而後插入一個新的元素 '小智'

const names = ['張三', '李四', '王五', '趙六']

names.splice(1, 2, '小智')

names //  ["張三", "小智", "趙六"]

提示:

  • array.splice() 會改變原數組。

11.4 展開操做符號

能夠經過組合展開操做符和數據字面量以不可變的方式從數組中刪除項。

const names = ['張三', '李四', '王五', '趙六']
const fromIndex = 1
const removeCount = 2

const newNames = [
   ...names.slice(0, fromIndex),
   ...names.slice(fromIndex + removeCount)
]

newNames // ["張三", "趙六"]

12. 清空數組

12.1 array.length屬性

array.length是保存數組長度的屬性。 除此以外,array.length是可寫的。

若是我們寫一個小於當前長度的array.length = newLength,多餘的元素從數組中移除。

以下所示:使用array.length = 0刪除數組中的全部項目:

const colors = ['blue', 'green', 'black'];

colors.length = 0;

colors; // []

12.2 array.splice() 方法

array.splice(fromIndex[, removeCount[, item1[, item2[, ...]]]])從數組中刪除元素,並插入新的元素。

若是removeCount參數被省略,那麼array.splice()將刪除從fromIndex開始的數組的全部元素。我們使用它來刪除數組中的全部元素:

const colors = ['blue', 'green', 'black'];

colors.splice(0);

colors; // []

13. 填充數組

13.1 array.fill() 方法

array.fill(value[, fromIndex[, toIndex]])用從fromIndextoIndex的值填充數組(不包括toIndex自己)。fromIndex可選參數默認爲0,toIndex可選參數默認爲array.length

例如,使用用零值填充數組:

const numbers = [1, 2, 3, 4];

numbers.fill(0);

numbers; // => [0, 0, 0, 0]

不只如此,還可使用Array(length).fill(initial)來初始化特定長度和初始值的數組。

const length = 3;
const zeros = Array(length).fill(0);

zeros; // [0, 0, 0]

提示:

  • array.splice() 會改變原數組。

13.2 Array.from() 函數

Array.from() 有助於初始化帶有對象的特定長度的數組:

const length = 4;
const emptyObjects = Array.from(Array(length), function() {
  return {};
});

emptyObjects; // [{}, {}, {}, {}]

14. 數組的扁平化

14.1 array.flat()方法

array.flat([depth])方法經過遞歸扁平屬於數組的項直到必定深度來建立新數組。 depth可選參數默認爲1

const arrays = [0, [1, 3, 5], [2, 4, 6]];

const flatArray = arrays.flat();

flatArray; // [0, 1, 3, 5, 2, 4, 6]

arrays 包含數字和數字數組的混合。 arrays.flat()對數組進行扁平,使其僅包含數字。

提示:

array.flat() 建立一個新數組,而不會改變原始數組。

15. 數組的排序

15.1 array.sort() 方法

array.sort([compare])方法對數組的元素進行排序。

可選參數compare(a, b)是一個自定義排序順的回調函數。若是比較compare(a, b)返回的結果:

  • 若是 a小於b,在排序後的數組中a應該出如今b以前,就返回一個小於0的值。
  • 若是a等於b,就返回0
  • 若是a大於b,就返回一個大於0的值。

以下所示,對數組 numbers 時行排序

const numbers = [4, 3, 1, 2];

numbers.sort();

numbers; // => [1, 2, 3, 4]

numbers.sort() 以升序對數字進行排序。

使用比較函數,讓偶數排在奇數前面:

const numbers = [4, 3, 1, 2];

function compare(n1, n2) {
  if (n1 % 2 === 0 && n2 % 2 !== 0) {
    return -1;
  }
  if (n1 % 2 !== 0 && n2 % 2 === 0) {
    return 1;
  }
  return 0;
}

numbers.sort(compare);

numbers; // => [4, 2, 3, 1]

提示:

  • array.sort() 會改變原數組。

原文:https://dmitripavlutin.com/op...

代碼部署後可能存在的BUG無法實時知道,過後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給你們推薦一個好用的BUG監控工具 Fundebug

交流

文章每週持續更新,能夠微信搜索「 大遷世界 」第一時間閱讀和催更(比博客早一到兩篇喲),本文 GitHub https://github.com/qq449245884/xiaozhi 已經收錄,整理了不少個人文檔,歡迎Star和完善,你們面試能夠參照考點複習,另外關注公衆號,後臺回覆福利,便可看到福利,你懂的。

相關文章
相關標籤/搜索