Array 是JavaScript中的一種資料格式,在JavaScript中會經常使用到;
作為前端工程師,掌握Array的用法是非常關鍵的!
那麼Array 常用的方法你又知道幾個呢?
本文将詳細介紹Array中常用的一些方法,一起學習一下吧!
本文内容:
- push()
- pop()
- shift()
- unshift()
- concat()
- slice()
- splice()
- join()
- indexOf()
- lastIndexOf()
- forEach()
- map()
- filter()
- reduce()
- sort()
- reverse()
- includes()
- some()
- every()
push
作用:向數組末尾添加一個或多個元素,并傳回數組的新長度
參數說明:element1, element2, ..., elementN 是要添加到數組末尾的元素。
示例用法:
1、添加單個元素到數組末尾;
const numbers = [1, 2, 3];
const length = numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]
console.log(length); // 4
2、添加多個元素到數組末尾;
const fruits = ['apple', 'banana'];
fruits.push('kiwi', 'orange');
console.log(fruits); // ['apple', 'banana', 'kiwi', 'orange']
pop
作用:删除并傳回數組的最後一個元素
注意:pop() 方法會修改原始數組,将數組的長度減一。
示例用法:
const fruits = ['apple', 'banana', 'kiwi'];
const removedElement = fruits.pop();
console.log(fruits); // ['apple', 'banana']
console.log(removedElement); // 'kiwi'
使用 pop方法删除數組最後一個元素;
shift
作用:删除并傳回數組的第一個元素
示例用法:
1、使用shift 删除元素,bing傳回被删除的元素;
const fruits = ['apple', 'banana', 'kiwi'];
const removedElement = fruits.shift();
console.log(fruits); // ['banana', 'kiwi']
console.log(removedElement); // 'apple'
2、如果删除的是空數組,結果将傳回 `undefined`;
const emptyArray = [];
const removedElement = emptyArray.shift();
console.log(emptyArray); // []
console.log(removedElement); // undefined
unshif
作用:向數組開頭添加一個或多個元素,并傳回數組的新長度
element1, element2, ..., elementN 是要添加到數組開頭的元素。
示例用法:
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']
concat
作用:将兩個或多個數組合并成一個新數組
value1, value2, ..., valueN 是要連接配接的數組或值。
示例用法:
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、連接配接數組和值:
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]
slice
作用:從數組中提取指定範圍的元素,傳回一個新數組
參數說明:
- start 是提取元素的起始位置的索引(包含該索引對應的元素);
- end 是提取元素的結束位置的索引(不包含該索引對應的元素);
如果不指定 end 參數,則提取從 start 索引位置到數組末尾的所有元素。
示例用法:
1、提取指定範圍的元素:
const fruits = ['apple', 'banana', 'kiwi', 'orange', 'grape'];
const slicedElements = fruits.slice(1, 4);
console.log(slicedElements); // ['banana', 'kiwi', 'orange']
2、提取從指定位置到數組末尾的元素:
const numbers = [1, 2, 3, 4, 5];
const slicedElementsToEnd = numbers.slice(2);
console.log(slicedElementsToEnd); // [3, 4, 5]
3、複制數組:
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = originalArray.slice();
console.log(copiedArray); // [1, 2, 3, 4, 5]
splice
作用:删除、替換或添加元素到數組的指定位置
參數說明:
- start 是要修改的起始位置的索引;
- deleteCount 是要删除的元素數量。
- 可以根據需要指定 item1、item2 等參數來插入新元素。
如果不指定 deleteCount,則删除從 start 索引位置開始之後的所有元素
示例用法:
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']
join
作用:将數組中的所有元素以指定的分隔符連接配接成一個字元串
separator 是一個可選的字元串參數,用于指定元素之間的分隔符,預設為逗号(,)。
示例用法:
1、将數組通過"-" 隔開;
const fruits = ['apple', 'banana', 'kiwi'];
const joinedString = fruits.join('-');
console.log(joinedString); // "apple-banana-kiwi"
2、預設使用逗号作為分隔符;
const numbers = [1, 2, 3, 4, 5];
const joinedStringDefault = numbers.join();
console.log(joinedStringDefault); // "1,2,3,4,5"
indexOf
作用:傳回指定元素在數組中首次出現的索引,如果未找到則傳回 -1。
示例用法:
1、搜尋第一次出現的下标位置;
const fruits = ['apple', 'banana', 'kiwi', 'banana', 'orange'];
const index = fruits.indexOf('banana');
console.log(index); // 1
2、搜尋指定位置的下标位置;
const numbers = [1, 2, 3, 4, 5, 3, 2, 1];
const indexFromIndex = numbers.indexOf(3, 3);
console.log(indexFromIndex); // 5
lastIndexOf
作用:傳回指定元素在數組中最後一次出現的索引,如果未找到則傳回 -1
示例用法:
1、搜尋數組中最後一次出現的下标位置;
const fruits = ['apple', 'banana', 'kiwi', 'banana', 'orange'];
const lastIndex = fruits.lastIndexOf('banana');
console.log(lastIndex); // 3
2、從指定位置開始搜尋最後一次出現的下标位置;
const numbers = [1, 2, 3, 4, 5, 3, 2, 1];
const lastIndexFromIndex = numbers.lastIndexOf(3, 4);
console.log(lastIndexFromIndex); // 2
forEach
作用:對數組中的每個元素執行指定的函數
forEach() 方法通常用于不需要傳回新數組的情況下,對數組中的每個元素執行操作。它提供了一種友善的方式來周遊數組并對每個元素執行相同的操作。
注意:forEach() 方法無法中斷或跳過疊代,它會周遊數組中的每個元素,即使在回調函數中使用了 return 語句也不會中止周遊。
map
作用:對數組中的每個元素執行指定的函數,并傳回執行結果組成的新數組
示例用法:
map() 方法可以根據自定義的處理邏輯對數組中的每個元素進行轉換。你可以使用它來生成新的數組,其中的元素是原始數組經過處理後的結果。常見的使用場景包括對數組中的每個元素進行計算、轉換、映射等操作。
filter
作用:根據指定的條件篩選出數組中符合條件的元素,傳回一個新數組
示例用法:
使用filter 方法,可以根據數組篩選出滿足特定條件的元素.
reduce
作用:對數組中的所有元素執行指定的歸約函數,傳回一個單值結果
參數說明:callback 是一個回調函數,可以接受四個參數:
- accumulator:累積器,用于儲存計算結果。
- currentValue:目前周遊到的元素。
- index:目前周遊到的元素的索引。
- array:正在被周遊的數組。
示例用法:
調用 reduce() 方法并傳入累加函數 (accumulator, currentValue) => accumulator + currentValue,即可對數組中的所有元素進行累加計算。初始累積器值未指定,是以 reduce() 方法從數組的第一個元素開始周遊,将目前元素與累積器相加,并更新累積器的值。最終,傳回的累積結果即為數組所有元素的累加和。
sort
作用:對數組元素進行排序
示例用法:
1、不傳參時調用 sort 會直接修改原始數組,并傳回排序後的數組;
2、傳入對比函數,對比較函數接受兩個參數,并傳回一個表示比較結果的數字;
reverse
作用:颠倒數組中元素的順序
通過使用 reverse() 方法,你可以友善地反轉數組中的元素順序,适用于需要颠倒數組内容的情況。
注意:reverse() 方法會直接修改原始數組,并不會建立新的數組。如果你需要保留原始數組的副本并進行反轉操作,可以先使用 slice() 方法建立一個新數組,然後再調用 reverse() 方法。
includes
作用:判斷數組是否包含指定元素,傳回 true 或 false
示例用法:
1、檢查數組中是否包含特定元素:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3)); // true
console.log(numbers.includes(6)); // false
2、使用 fromIndex 參數指定搜尋的起始位置:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3, 2)); // true,從索引 2 開始搜尋
console.log(numbers.includes(3, 4)); // false,從索引 4 開始搜尋
3、檢查數組中是否包含字元串:
const fruits = ['apple', 'banana', 'kiwi', 'pear'];
console.log(fruits.includes('banana')); // true
console.log(fruits.includes('grape')); // false
some
作用:檢測數組中是否有至少一個元素滿足指定條件,傳回 true 或 false
示例用法:
1、檢查數組中是否存在大于 10 的元素:
const numbers = [5, 8, 12, 3, 9];
const hasGreaterThan10 = numbers.some(element => element > 10);
console.log(hasGreaterThan10); // true
2、檢查數組中是否存在偶數:
const numbers = [3, 7, 5, 12, 9];
const hasEvenNumber = numbers.some(element => element % 2 === 0);
console.log(hasEvenNumber); // true
3、檢查數組中是否存在包含特定字元的字元串:
const fruits = ['apple', 'banana', 'kiwi', 'pear'];
const hasStrWithChar = fruits.some(element => element.includes('a'));
console.log(hasStrWithChar); // true
4、檢查數組中是否存在滿足複雜條件的元素:
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
every
作用:檢測數組中是否所有元素都滿足指定條件,傳回 true 或 false
示例用法:
- 檢查數組中的所有元素是否都大于 0:
const numbers = [5, 8, 12, 3, 9];
const allGreaterThan0 = numbers.every(element => element > 0);
console.log(allGreaterThan0); // true
- 檢查數組中的所有元素是否都是偶數:
const numbers = [2, 4, 6, 8, 10];
const allEvenNumbers = numbers.every(element => element % 2 === 0);
console.log(allEvenNumbers); // true
- 檢查數組中的所有字元串是否都以大寫字母開頭:
const words = ['Apple', 'Banana', 'Cherry', 'Durian'];
const allUpperCaseStart = words.every(element => /^[A-Z]/.test(element));
console.log(allUpperCaseStart); // true
- 檢查數組中的所有對象是否都滿足特定條件:
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
Array 在ES6中還有一些更進階的使用方法,能夠更快捷的操作Array。
以上就是今天分享的19個Array常用的方法,你學會了嗎?
說明:本文首發頭條,歡迎轉載!轉載請标注來源即可,無需授權!創作不易,喜歡我的文章,記得添加【關注】哦!再次感謝你的支援!
❀ 長按【點贊】會有驚喜哦!❀
~End~