ES6
(ECMAScript 2015
)是 JavaScript
語言的一個重要版本,為編寫更加簡潔、便捷和可讀性更高的代碼提供了很多新的特性和 API。想了解ES6所有新增API,可以跳轉(zhuǎn)至我的另一篇博客:JS語法 ES6、ES7、ES8、ES9、ES10、ES11、ES12新特性
其中數(shù)組相關(guān)的 API 也在 ES6 中得到了大大的增強(qiáng),下面我來詳細(xì)介紹一下 ES6 中數(shù)組的新特性和 API。
1. Array.of()
Array.of()
方法創(chuàng)建一個新的數(shù)組,根據(jù)傳入?yún)?shù)創(chuàng)建數(shù)組元素。
- 傳入的參數(shù)可以是任意數(shù)據(jù)類型,且不需要指定數(shù)組長度。
- 如果沒有參數(shù),則返回一個空數(shù)組
- 與傳統(tǒng)的數(shù)組字面量創(chuàng)建方式相比,Array.of() 的行為更加明確和可預(yù)期。
舉個例子,可以創(chuàng)建一個包含三個元素的數(shù)組,如下所示:
const arr = Array.of(1, 2, 3);
console.log(arr); // output: [1, 2, 3]
在這個示例中,我們使用 Array.of() 方法創(chuàng)建了一個包含三個整數(shù)的數(shù)組,并將其分配給變量 arr。請注意,由于我們傳遞了三個參數(shù),因此創(chuàng)建的數(shù)組包含三個元素。
Array.of()
方法的主要優(yōu)點是它可以創(chuàng)建一個指定長度的數(shù)組,而不必使用 Array() 方法的特殊語法。例如,如果要創(chuàng)建一個包含五個元素的數(shù)組,可以如下所示:
const arr = Array.of(5);
console.log(arr); // output: [5]
在此示例中,我們傳遞了一個整數(shù) 5,這將創(chuàng)建一個包含一個元素的數(shù)組,該元素的值為 5。請注意,這與使用 Array() 方法的創(chuàng)建方式不同:
const arr = new Array(5);
console.log(arr); // output: [ , , , , ]
在此示例中,我們創(chuàng)建了一個包含五個元素的數(shù)組,并將其分配給變量 arr。請注意,在創(chuàng)建時,這個數(shù)組沒有給出任何元素值。這與使用Array.of()方法不同,它使用任意數(shù)量的參數(shù)來初始化一個數(shù)組,因此如果要設(shè)置值,可以采用以下方式自動列表形式:
const arr = Array.of(1, 2, 3, 4, 5);
console.log(arr); // output: [1, 2, 3, 4, 5]
另外,要注意 Array.of() 方法在創(chuàng)建包含一個字符串元素時的用法。在這種情況下,字符串會被視為單個元素,而不是將字符串拆分為單個字符。
const arr = Array.of("hello");
console.log(arr); // output: ["hello"]
總之,
Array.of()
方法提供了一種簡單的方式來創(chuàng)建自定義大小的數(shù)組并初始化其中的元素。
2. Array.from()
Array.from()
方法從類似數(shù)組或可迭代對象(如 Set 或 Map)創(chuàng)建一個新的數(shù)組實例。該方法還支持隱式映射和過濾器參數(shù)。
例如,要從 Set 對象 mySet
中創(chuàng)建一個數(shù)組,可以使用以下方式:
const mySet = new Set([1, 2, 3]);
const arr = Array.from(mySet);
console.log(arr); // [1, 2, 3]
可以利用第二個參數(shù)完成隱式映射,接收一個函數(shù)用來映射元素:
const arr = Array.from([1, 2, 3], x => x * 2);
console.log(arr); // [2, 4, 6]
3. Array.prototype.fill()
Array.prototype.fill()
方法會將數(shù)組中的所有元素替換為指定的值。它接受三個參數(shù):value
(必填),start
(可選)和end
(可選)。
-
value
參數(shù)為填充數(shù)組元素使用的值。 -
start
參數(shù)表示開始填充的位置,如果不指定,默認(rèn)為0。 -
end
參數(shù)表示填充的結(jié)束位置,但不包括結(jié)束位置本身。如果未傳遞 end 參數(shù),則 default 為數(shù)組末尾。
舉個例子,我們可以使用 fill() 方法將數(shù)組中所有的元素設(shè)置為相同的值:
// 創(chuàng)建一個5個元素的空數(shù)組
const arr = new Array(5);
// 用數(shù)字0填充數(shù)組
arr.fill(0);
console.log(arr); // output: [0, 0, 0, 0, 0]
如上所示, 我們首先創(chuàng)建一個包含5個元素的空數(shù)組,并將其分配給變量 arr。接下來,我們使用 fill()
方法將數(shù)組中的所有元素設(shè)置為數(shù)字 0。
下面的例子演示了使用 start 和 end 參數(shù)來填充數(shù)組中的一個特定子集:
// 創(chuàng)建一個5個元素的空數(shù)組
const arr = new Array(5);
// 用數(shù)字1來填充數(shù)組的第2個到第4個元素
arr.fill(1, 1, 4);
console.log(arr); // output: [ , 1, 1, 1, ]
如上所示,我們首先初始化了一個包含5個元素的空數(shù)組,并將其分配給變量 arr。接下來,我們使用 fill()
方法將數(shù)組的第2
,第3
和第4
個元素設(shè)置為數(shù)字 1
,同時指定了 start 參數(shù)為 1(表示第二個元素)和 end 參數(shù)為 4(表示第五個元素的索引)。
值得一提的是,
fill()
方法操作的是原數(shù)組
,并返回修改后的數(shù)組,因此不需要創(chuàng)建新數(shù)組。- 如果需要創(chuàng)建一個新的數(shù)組,則可以使用
Array.from()
方法和fill()
方法的結(jié)合:
const n = 5;
const arr = Array.from({length: n}, () => 0);
console.log(arr); // output: [0, 0, 0, 0, 0]
在上面的示例中,我們使用 Array.from() 方法和一個箭頭函數(shù)生成一個長度為 n 的數(shù)組,并用 0 進(jìn)行填充,獲得一個新的包含 n 個元素的數(shù)組。
總之,
Array.fill()
方法提供了一種快速設(shè)置大量數(shù)組的元素值的方式,它可以輕松地操作原始數(shù)組。
4. Array.prototype.copyWithin()
Array.copyWithin()
方法用給定數(shù)組中的一段內(nèi)容向另一位置拷貝,用原數(shù)組中的值加以覆蓋。它接受三個參數(shù):target、start 和 end。
-
target
表示拷貝到該位置的下標(biāo)索引, -
start
和end
表示需要拷貝的部分的開始和結(jié)束位置(start 位置的元素會包括在拷貝的部分中,end 位置的元素不包括其中)。如果有需要,方法會在進(jìn)行拷貝操作前將數(shù)組縮小或擴(kuò)大為所需大小。
下面的例子演示了如何使用 copyWithin()
方法:
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3, 4);
console.log(arr); // output: [4, 2, 3, 4, 5]
如上所示,我們首先定義了一個包含 5 個整數(shù)的數(shù)組,并將其分配給變量 arr
。然后,我們使用 arr.copyWithin()
方法,將 從數(shù)組下標(biāo) 3
開始的一項 拷貝到 數(shù)組下標(biāo) 0
,覆蓋原始的前三項
。 這個 copyWithin() 方法會在原數(shù)組
上操作,這也是為什么拷貝的值從原數(shù)組的第一個位置開始的原因。
下面我們來詳細(xì)說明一下這個方法的參數(shù):
-
target
: 必填參數(shù)。從該位置開始替換數(shù)據(jù)。如果是負(fù)數(shù),則表示從 array.length + target 開始替換(即從數(shù)組末尾倒著數(shù)的位置)。 -
start
: 必填參數(shù)。從該位置開始讀取數(shù)據(jù),默認(rèn)是0。如果是負(fù)數(shù),則表示從 array.length + start 開始讀?。磸臄?shù)組末尾倒著數(shù)的位置)。 -
end
: 可選參數(shù)。到該位置前停止讀取數(shù)據(jù),默認(rèn)是array.length。如果是負(fù)數(shù),則表示從 array.length + end 開始停止讀?。磸臄?shù)組末尾倒著數(shù)的位置)。
需要注意的是:
target
、start
和end
參數(shù)都必須是整數(shù),不然會自動取整。- 該方法無法使用于
const
聲明的數(shù)組,因為它會修改原數(shù)組。
總之,
Array.copyWithin()
方法提供了一種快速交換、移動和復(fù)制數(shù)組元素的方式。
5. Array.prototype.find() 和 Array.prototype.findIndex()
-
Array.prototype.find()
方法用于查找符合條件的第一個數(shù)組元素,將該元素返回。類似地, -
Array.prototype.findIndex()
方法也可以查找符合條件的第一個元素,并將該元素的索引返回。如果找不到符合條件的元素,則返回undefined
。
例如,查找數(shù)組 [1,2,3,4,5]
中第一個大于 3 的數(shù),可以使用以下方式:
const arr = [1,2,3,4,5];
const index = arr.find(item => item > 3);
const index2 = arr.findIndex(item => item > 3);
console.log(index); // 4
console.log(index2); // 3
6. Array.prototype.some() 和 Array.prototype.every()
-
Array.prototype.some()
方法檢查數(shù)組中是否有一個或多個元素符合條件。該方法會返回布爾值 true 或 false。- -
Array.prototype.every()
方法則檢查數(shù)組中的所有元素是否都符合條件。如果符合條件,則返回 true,否則返回 false。
例如,檢查數(shù)組 [2, 3, 4, 5]
中是否存在一個大于 3 的數(shù),可以使用以下方式:
const arr = [2,3,4,5];
const hasGreaterThanThree = arr.some(item => item > 3);
const allGreaterThanOne = arr.every(item => item > 1);
console.log(hasGreaterThanThree); // true
console.log(allGreaterThanOne); // true
7. Array.prototype.flat()
Array.prototype.flat()
方法用于遞歸地展開一個數(shù)組,將嵌套的數(shù)組變成一個一維的數(shù)組。該方法的默認(rèn)展開深度為1
,可以接受一個可選的整數(shù)參數(shù),表示展開的深度。如果參數(shù)為 Infinity
,則遞歸將一直執(zhí)行,直到展開為一維數(shù)組。
例如,將嵌套數(shù)組 [[1,2,3],[4,5]]
展開為一維數(shù)組,可以使用以下方式:
const arr = [[1,2,3],[4,5]];
const flattened = arr.flat();
console.log(flattened); // [1, 2, 3, 4, 5]
如果已經(jīng)知道要展開多少層,可以將數(shù)值作為參數(shù)傳遞給
flat
方法:
例如,將嵌套數(shù)組 [[1,[2,3]],[4,[5,6]]]
展開為一維數(shù)組:
const arr = [[1,[2,3]],[4,[5,6]]];
const flattenedOnce = arr.flat(1);
console.log(flattenedOnce); // [1, [2, 3], 4, [5, 6]]
const flattenedTwice = arr.flat(2);
console.log(flattenedTwice); // [1, 2, 3, 4, 5, 6]
需要注意的是,
flat()
方法不改變原數(shù)組,而是返回一個新的數(shù)組,適用于不會改變原有數(shù)據(jù)的語境中。如果原數(shù)組中包含null
或者undefined
,它們會被自動跳過。
還有需要注意的地方是,
flat()
方法雖然方便,但也可能會產(chǎn)生性能問題和邏輯問題。對于嵌套非常深的數(shù)組,如果直接使用flat()
方法,會喪失代碼的可讀性和可維護(hù)性。如果有嵌套不確定深度的數(shù)組,最好使用遞歸的方法來展開數(shù)組,或使用第三方庫,可以避免展開時出現(xiàn)的性能和邏輯問題。
8、Array.prototype.flatMap()
Array.prototype.flatMap()
方法是在ES2019標(biāo)準(zhǔn)下引入的一個新的數(shù)組方法,它結(jié)合了 Array.prototype.map()
和 Array.prototype.flat()
兩個方法的功能。flatMap()
方法可以將數(shù)組按照一定的規(guī)則“展平”為一個新的數(shù)組,與 flat() 方法很相似,但又比 flat()
更加靈活。
flatMap()
方法首先使用 map()
方法根據(jù)指定規(guī)則進(jìn)行對數(shù)組元素進(jìn)行操作,然后將處理后的數(shù)組“拉平”為一個一維數(shù)組。與 map() 和 flat() 方法不同之處在于,flatMap() 方法將這兩個操作結(jié)合在了一起,避免了使用 map() 和 flat() 時需要寫額外的代碼。
例如,我們有一個數(shù)組,要將每個元素乘以2,然后取出其中偶數(shù)值,可以使用以下方式:
const arr = [1, 2, 3, 4];
const result = arr.flatMap(x => x * 2).filter(x => x % 2 === 0);
console.log(result); // [4, 8]
在上述代碼中,我們首先使用 map()
方法將數(shù)組中每個元素乘以2
,然后使用 flat()
方法將結(jié)果展開為一維數(shù)組,并使用 filter()
方法過濾出偶數(shù)值。
需要注意的是,
flatMap()
方法會跳過值為null
或者undefined
的數(shù)組元素,在無需考慮這兩種元素的情況下,可以得到更加清晰和簡潔的代碼。flatMap()
方法在在一些場合下可能會有越界異常的問題
產(chǎn)生,所以在使用時需要適當(dāng)注意范圍越界等問題。
9. Array.prototype.keys()、Array.prototype.entries()和Array.prototype.values()
ES6中將三個迭代方法添加到數(shù)組的原型中:keys()
、entries()
和values()
。
Array.prototype.keys()
方法返回一個迭代器,該迭代器包含數(shù)組中的每個元素的索引。
const arr = ['a', 'b', 'c'];
const iterator = arr.keys();
console.log(iterator.next().value); // 0
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
與之相似,Array.prototype.entries()
方法返回一個包含數(shù)組中每個元素的鍵/值對的迭代器。
const arr = ['a', 'b', 'c'];
const iterator = arr.entries();
console.log(iterator.next().value); // [0, 'a']
console.log(iterator.next().value); // [1, 'b']
console.log(iterator.next().value); // [2, 'c']
Array.prototype.values()
返回一個包含數(shù)組中每個元素的值的迭代器。
const arr = ['a', 'b', 'c'];
const iterator = arr.values();
console.log(iterator.next().value); // 'a'
console.log(iterator.next().value); // 'b'
console.log(iterator.next().value); // 'c'
10. Array.prototype.reduceRight()
Array.prototype.reduceRight()
方法與reduce()
方法非常相似,但是遍歷的順序是從后往前的。
const arr = ['a', 'b', 'c'];
const result = arr.reduceRight((prev, cur) => prev + cur);
console.log(result); // 'cba'
11. Array.prototype.sort()
Array.prototype.sort()
方法用于對數(shù)組進(jìn)行排序,可以傳遞一個函數(shù)以根據(jù)一些基準(zhǔn)進(jìn)行排序。在ES6之前,排序從左到右進(jìn)行,這可能會影響排序的結(jié)果。在ES6中,Array.prototype.sort()
方法默認(rèn)使用穩(wěn)定的排序算法,并按照Unicode
字符順序進(jìn)行排序。
const arr = [1,4,3,8,5,2];
arr.sort((a,b) => a-b);
console.log(arr); // [1, 2, 3, 4, 5, 8]
12. Array.prototype.includes()
Array.prototype.includes()
方法用于判斷一個數(shù)組是否包含某個元素,如果包含則返回 true
,否則返回 false
。與 Array.prototype.indexOf()
方法不同的是,includes()
方法支持檢查 NaN
的存在。
例如,判斷數(shù)組 [1, 2, 3]
是否包含元素 2
和 4
,可以使用以下方式:
const arr = [1, 2, 3];
console.log(arr.includes(2)); // true
console.log(arr.includes(4)); // false
13. Array.prototype.findIndex()
Array.prototype.findIndex()
方法返回數(shù)組中第一個符合條件的元素的索引,如果沒有符合條件的元素,則返回 -1
。
例如,查找數(shù)組 [1, 2, 3, 4, 5]
中第一個大于 3
的元素的索引,可以使用以下方式:
const arr = [1, 2, 3, 4, 5];
const index = arr.findIndex(item => item > 3);
console.log(index); // 3
14. 數(shù)組解構(gòu)語法( Array destructuring )
ES6 中引入了數(shù)組解構(gòu)語法,可以通過將數(shù)組的元素分配給變量來快速訪問和使用這些元素。
例如,要將數(shù)組 [1, 2, 3]
中的元素分別賦值給變量 x
、y
和 z
,可以使用以下方式:
const [x, y, z] = [1, 2, 3];
console.log(x); // 1
console.log(y); // 2
console.log(z); // 3
在此基礎(chǔ)上,我們還可以使用擴(kuò)展運(yùn)算符來獲取數(shù)組中的剩余元素:
const [x, ...rest] = [1, 2, 3];
console.log(x); // 1
console.log(rest); // [2, 3]
15. Array.from() 與 Array.of() 方法的區(qū)別
ES6 中的 Array.from()
和 Array.of()
方法都被用來創(chuàng)建新數(shù)組,但它們的行為略有不同。
-
Array.of()
方法可以根據(jù)傳入的參數(shù)創(chuàng)建一個新的數(shù)組實例,并且會將傳入的參數(shù)作為元素添加到新的數(shù)組中:const arr = Array.of(1, 2, 3); console.log(arr); // [1, 2, 3]
-
Array.from()
方法則可以將類似數(shù)組或可迭代對象轉(zhuǎn)換成數(shù)組實例。該方法還接受一個可選的 map() 函數(shù),可以使用該函數(shù)對每個元素進(jìn)行轉(zhuǎn)換:const arr1 = Array.from('foo'); console.log(arr1); // ['f', 'o', 'o'] const arr2 = Array.from([1, 2, 3], x => x * 2); console.log(arr2); // [2, 4, 6]
16、 push()、pop()、shift() 和 unshift() 方法的改進(jìn)
// push() 方法示例
const arr1 = [1, 2, 3];
arr1.push(4, 5); // 在數(shù)組尾部插入多個元素
console.log(arr1); // [1, 2, 3, 4, 5]
// pop() 方法示例
const arr2 = [1, 2, 3];
const last = arr2.pop(); // 彈出數(shù)組末尾元素
console.log(last); // 3
console.log(arr2); // [1, 2]
// shift() 方法示例
const arr3 = [1, 2, 3];
const first = arr3.shift(); // 彈出數(shù)組頭部元素
console.log(first); // 1
console.log(arr3); // [2, 3]
// unshift() 方法示例
const arr4 = [1, 2, 3];
arr4.unshift(-1, 0); // 在數(shù)組頭部插入多個元素
console.log(arr4); // [-1, 0, 1, 2, 3]
通過傳入多個參數(shù),數(shù)組方法 push()
、unshift()
可以一次性向數(shù)組尾部或頭部添加多個元素。相比于多次使用 push() 或 unshift() 方法,這種方式更加高效、簡潔。
17、map()、reduce() 和 filter() 方法的鏈?zhǔn)秸{(diào)用
ES6 中數(shù)組的 map()
、reduce()
和 filter()
方法都支持鏈?zhǔn)秸{(diào)用,能夠讓我們更加優(yōu)雅地操作數(shù)組。
例如下面的代碼就使用 reduce()
和 filter()
方法鏈?zhǔn)秸{(diào)用,將數(shù)組中所有大于 2 的元素相乘:
const arr = [1, 2, 3, 4];
const result = arr.filter(item => item > 2)
.reduce((prev, curr) => prev * curr, 1);
console.log(result); // 12
上面的代碼中,我們首先使用 filter()
方法篩選出大于 2 的元素,然后將這些元素使用 reduce()
方法相乘,最終得到了結(jié)果 12。鏈?zhǔn)秸{(diào)用將減少了不必要的中間變量,代碼更加簡潔高效。
18. Array.prototype[@@species]
ES6 中新增了一個用于創(chuàng)建派生類的屬性 @@species
,它是一個函數(shù)對象,用于創(chuàng)建派生類的構(gòu)造函數(shù)。在派生類中,如果重寫了 Symbol.species
屬性,則它將使用重寫后的 @@species
屬性來創(chuàng)建新實例。
下面的示例代碼中,我們定義了一個名為 MyArray
的派生類,它繼承自 Array 類,并重寫了 Symbol.species
屬性:
class MyArray extends Array {
static get [Symbol.species]() { return Array; }
}
const arr1 = new MyArray(1, 2, 3);
const arr2 = arr1.map(x => x * x);
console.log(arr1 instanceof MyArray); // true
console.log(arr2 instanceof MyArray); // false
console.log(arr2 instanceof Array); // true
上面的代碼中,MyArray
類重寫了 Symbol.species
屬性,將返回 Array
,因此在調(diào)用 map()
方法后返回的新數(shù)組實例就是 Array 類型,而非 MyArray 類型。文章來源:http://www.zghlxwxcb.cn/news/detail-489364.html
總結(jié)
ES6 中的數(shù)組 API 帶來了很多變化,讓我們操作數(shù)組的效率更高,代碼變得更簡潔。在日常開發(fā)過程中,可以多加使用這些 API,提高代碼的工作效率和開發(fā)質(zhì)量。文章來源地址http://www.zghlxwxcb.cn/news/detail-489364.html
到了這里,關(guān)于【JavaScript】探索ES6中的數(shù)組API:簡潔高效的操作方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!