溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JS中常見的數(shù)組操作方法有哪些

發(fā)布時間:2022-05-26 11:38:14 來源:億速云 閱讀:138 作者:iii 欄目:大數(shù)據(jù)

本篇內(nèi)容介紹了“JS中常見的數(shù)組操作方法有哪些”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

數(shù)組是 JS 中廣泛使用的數(shù)據(jù)結(jié)構(gòu)。數(shù)組對象提供了大量有用的方法,如array. forEach()、array.map()等來操作數(shù)組。

1. 數(shù)組的遍歷

1.1  for..of 循環(huán)

for(const item of items)循環(huán)遍歷數(shù)組項,如下所示遍歷colors列表:

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

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

提示:

咱們可以隨時使用break語句停止遍歷。

1.2 for 循環(huán)

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

for通常需要在每個循環(huán)中遞增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)方法通過在每個數(shù)組項上調(diào)用callback函數(shù)來遍歷數(shù)組項。

在每次遍歷中,都使用以下參數(shù)調(diào)用callback(item [, index [, array]]):當前遍歷項,當前遍歷索引和數(shù)組本身。

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

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

提示:

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

2. 數(shù)組的映射

2.1 Array.map()方法

array.map(callback) 方法通過在每個數(shù)組項上使用callback調(diào)用結(jié)果來創(chuàng)建一個新數(shù)組。

在每個遍歷中的callback(item[, index[, array]])使用參數(shù)調(diào)用:當前項、索引和數(shù)組本身,并應(yīng)該返回新項。

如下所示咱們對每個數(shù)組元素都遞增 1:

const numbers = [0, 2, 4];

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

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

提示:

array.map()創(chuàng)建一個新的映射數(shù)組,而不改變原始數(shù)組。

2.2 Array.from()方法

Array.from(arrayLike[, callback])方法通過在每個數(shù)組項上使用callback 調(diào)用結(jié)果來創(chuàng)建一個新數(shù)組。

在每個遍歷中callback(item[, index[, array]])使用參數(shù)調(diào)用:當前項、索引和數(shù)組本身并且應(yīng)該返回新項。

如下所示咱們對每個數(shù)組元素都遞增 1:

const numbers = [0, 2, 4];

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

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

提示:

Array.from()創(chuàng)建一個新的映射數(shù)組,而不改變原始數(shù)組。Array.from()更適合從類似數(shù)組的對象進行映射。

3. 數(shù)據(jù)的簡化

3.1 Array.reduce() 方法

array.reduce(callback[, initialValue])通過調(diào)用callback 函數(shù)來將數(shù)組簡化為一個值。

在每次遍歷中的callback(accumulator, item[, index[, array]])使用用參數(shù)調(diào)用的:累加器,當前項,索引和數(shù)組本身且應(yīng)該返回累加器。

經(jīng)典示例是對數(shù)字數(shù)組求和:

const numbers = [2, 0, 4];

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

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

sum; // => 6

第一步,將accumulator 初始化為0。然后,對每個累加數(shù)字和的數(shù)組項調(diào)用summary函數(shù)。

提示:

如果沒有使用 initialValue 來設(shè)置初始值,則默認使用數(shù)組的第一個元素作為初始值。

4. 數(shù)據(jù)的連接

4.1 array.concat() 方法

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

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

const everyone = heroes.concat(villains);

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

提示:

concat()創(chuàng)建一個新的數(shù)組,而不改變原來的數(shù)組array.concat(array1 [,array2,...]) 接受多個要連接的數(shù)組。

4.2 展開操作符號

咱們將展開操作符與數(shù)組字面量一起使用來連接數(shù)組:[...array1, ...array2]。

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

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

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

提示:

[...arr1, ...arr2, ...arrN]:咱們可以使用展開運算符連接所需數(shù)量的數(shù)組。

獲取數(shù)組的片段

5.1 array.slice()  方法

array.slice([fromIndex [,toIndex]])返回數(shù)組的一個片段,該片段從fromIndex開始,以toIndex結(jié)尾(不包括toIndex本身)。fromIndex可選參數(shù)默認為0,toIndex可選參數(shù)默認為array.length。

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

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

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

提示:

array.slice() 創(chuàng)建一個新數(shù)組,而不改變原始數(shù)組。

6. 數(shù)組的拷貝

6.1 展開操作符

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

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

const clone = [...colors];

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

提示:

[...array] 創(chuàng)建一個淺拷貝。

6.2 array.concat()方法

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

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

const clone = [].concat(colors);

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

提示:

[].concat(array) 創(chuàng)建一個淺拷貝。

6.3 array.slice() 方法

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

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

const clone = colors.slice();

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

提示:

colors.slice() 創(chuàng)建一個淺拷貝。

7. 查找數(shù)組

7.1 array.includes() 方法

array.includes(itemToSearch [,fromIndex])返回一個布爾值,array 是否包含itemToSearch。 可選參數(shù)fromIndex,默認為0,表示開始搜索的索引。如下所示:判斷2和99是否存在于一組數(shù)字中:

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

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

7.2  array.find() 方法

array.find(predicate) 方法返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的值。否則返回 undefined。

如下所示,找到數(shù)組中的第一個偶數(shù):

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中第一個出現(xiàn)的itemToSearch的索引。默認為0的可選參數(shù)fromIndex表示開始搜索的索引。

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

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

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

index // 1

提示:

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

8. 查詢數(shù)組

8.1 array.every() 方法

如果每個項都通過predicate 檢查,則array.every(predicate)返回true。

在每個遍歷predicate(item[, index[, array]])上,用參數(shù)調(diào)用predicate 函數(shù):當前遍歷項、索引和數(shù)組本身。

如下所示,確定數(shù)組是否只包含偶數(shù):

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]])上,用參數(shù)調(diào)用predicate 函數(shù):當前遍歷項、索引和數(shù)組本身。

如下所示:確定數(shù)組是否至少包含一個偶數(shù):

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. 數(shù)組的過濾

9.1 array.filter() 方法

array.filter(predicate)方法創(chuàng)建一個新數(shù)組, 其包含通過所提供函數(shù)實現(xiàn)的測試的所有元素。

在每個遍歷predicate(item[, index[, array]])上,用參數(shù)調(diào)用predicate 函數(shù):當前遍歷項、索引和數(shù)組本身。

如下所示:將一個數(shù)組過濾為僅包含偶數(shù):

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

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

const evens = numbers.filter(isEven);

evens; // => [10]

提示:

array.filter() 創(chuàng)建一個新數(shù)組,而不改變原始數(shù)組。

10. 數(shù)組的插入

10.1 array.push() 方法

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

如下所示,在names 數(shù)組的末尾添加 '小智'

const names = ['小智']

names.push('前端小智')

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

提示:

array.push() 會改變原數(shù)組array.push(item1, item2, ..., itemN) 可以添加多個元素。

10.2 array.unshift() 方法

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

const names = ['小智']

names.unshift('前端小智')

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

提示:

array.unshift() 會改變原數(shù)組array.unshift(item1, item2, ..., itemN) 可以添加多個元素。

10.3 展開操作符

可以通過組合展開操作符和數(shù)組字面量以不可變的方式在數(shù)組中插入項。

在數(shù)組末尾追加一個項:

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

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

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

在數(shù)組的開頭追加一個項:

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

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

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

在任何索引處插入元素:

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

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

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

11. 刪除數(shù)組元素

11.1 array.pop() 方法

array.pop()方法從數(shù)組中刪除最后一個元素,然后返回該元素。如下所示,刪除colors數(shù)組的最后一個元素:

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

const lastColor = colors.pop();

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

提示:

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

11.2 array.shift() 方法

array.shift()方法從數(shù)組中刪除第一個元素,然后返回該元素。

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

const firstColor = colors.shift();

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

提示:

array.shift() 會改變原數(shù)組。

array.shift() 具有O(n)復(fù)雜度。

11.3 array.splice() 方法

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

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

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

names.splice(1, 2)

names // => ["張三", "趙六"]復(fù)制代碼

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

names.splice() 可以插入新元素,而不是插入已刪除的元素。 咱們可以替換索引1處開始的的2個元素,然后插入一個新的元素 '小智':

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

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

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

提示:

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

11.4 展開操作符號

可以通過組合展開操作符和數(shù)據(jù)字面量以不可變的方式從數(shù)組中刪除項。

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

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

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

12. 清空數(shù)組

12.1 array.length屬性

array.length是保存數(shù)組長度的屬性。 除此之外,array.length是可寫的。

如果咱們寫一個小于當前長度的array.length = newLength,多余的元素從數(shù)組中移除。

如下所示:使用array.length = 0刪除數(shù)組中的所有項目:

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

colors.length = 0;

colors; // []

12.2 array.splice() 方法

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

如果removeCount參數(shù)被省略,那么array.splice()將刪除從fromIndex開始的數(shù)組的所有元素。咱們使用它來刪除數(shù)組中的所有元素:

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

colors.splice(0);

colors; // []

13. 填充數(shù)組

13.1 array.fill() 方法

array.fill(value[, fromIndex[, toIndex]])用從fromIndex 到toIndex的值填充數(shù)組(不包括toIndex本身)。fromIndex可選參數(shù)默認為0,toIndex可選參數(shù)默認為array.length。

例如,使用用零值填充數(shù)組:

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

numbers.fill(0);

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

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

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

zeros; // [0, 0, 0]

提示:

array.fill() 會改變原數(shù)組。

13.2 Array.from() 函數(shù)

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

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

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

14. 數(shù)組的扁平化

14.1 array.flat()方法

array.flat([depth])方法通過遞歸扁平屬于數(shù)組的項直到一定深度來創(chuàng)建新數(shù)組。 depth可選參數(shù)默認為1:

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

const flatArray = arrays.flat();

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

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

提示:

array.flat() 創(chuàng)建一個新數(shù)組,而不會改變原始數(shù)組。

15. 數(shù)組的排序

15.1 array.sort() 方法

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

可選參數(shù)compare(a, b)是一個自定義排序順的回調(diào)函數(shù)。如果比較compare(a, b)返回的結(jié)果:

如果 a小于b,在排序后的數(shù)組中a應(yīng)該出現(xiàn)在b之前,就返回一個小于0的值。如果a等于b,就返回0。如果a大于b,就返回一個大于0的值。

如下所示,對數(shù)組 numbers 時行排序

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

numbers.sort();

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

numbers.sort() 以升序?qū)?shù)字進行排序。

使用比較函數(shù),讓偶數(shù)排在奇數(shù)前面:

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() 會改變原數(shù)組。

“JS中常見的數(shù)組操作方法有哪些”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

js
AI