>本文探討了幾種新的ES6方法增強數組操縱,分為Array.*
>(類方法)和Array.prototype.*
(實例方法)。 我們將通過示例檢查它們的用法,並討論多填充以獲得更廣泛的兼容性。 Paul Miller提供的es6-shim
提供了一個全面的解決方案,用於填充這些方法。
密鑰概念:
Array.from()
,Array.prototype.find()
,Array.prototype.findIndex()
,Array.prototype.keys()
,Array.prototype.values()
和Array.prototype.fill()
。
Array.from()
Array.prototype.find()
找到滿足給定測試功能的第一個數組元素。 Array.prototype.findIndex()
返回元素本身; find()
返回其索引。 兩者都有很好的支持,不包括Internet Explorer。
findIndex()
Array.prototype.keys()
>在給定範圍內具有指定值的數組。 這些方法具有廣泛的支持,不包括Internet Explorer。
Array.prototype.values()
Array.prototype.fill()
Array.from()
>從類似陣列或具有峰值的來源創建一個數組。 這解決了傳統的解決方法:
Array.from()
>語法:[].slice.call(arrayLike)
>參數:
Array.from(arrayLike[, mapFn[, thisArg]])
arrayLike
:應用於每個元素的函數。 mapFn
:thisArg
>示例:倍增函數參數:this
mapFn
function double(...args) { return Array.from(args, elem => elem * 2); } console.log(double(1, 2, 3, 4)); // Output: [2, 4, 6, 8]
>返回滿足提供的測試功能的第一個元素。 Array.prototype.find()
>語法:
>回調參數:Array.prototype.find()
Array.prototype.find(callback[, thisArg])
element
:陣列。 index
>示例:查找大於2:array
支持:除了Internet Explorer以外,得到了廣泛支持。 MDN上有一個polyfill。
const arr = [1, 2, 3, 4]; const result = arr.find(elem => elem > 2); console.log(result); // Output: 3
>類似於find()
>,但返回第一個匹配元素的索引,或-1,如果沒有找到。
支持:除了Internet Explorer以外,得到了廣泛支持。 MDN上有一個polyfill。
Array.from(arrayLike[, mapFn[, thisArg]])
和
Array.prototype.keys()
>
Array.prototype.values()
這些方法分別返回鍵和值的數組迭代器。 >
支持:
>除了Internet Explorer以外,還具有良好的支持。function double(...args) { return Array.from(args, elem => elem * 2); } console.log(double(1, 2, 3, 4)); // Output: [2, 4, 6, 8]
keys()
values()
Array.prototype.fill()
>填充帶有指定值的數組。
Array.prototype.fill()
>示例:
支持:除了Internet Explorer以外,得到了廣泛支持。 Polyfills可在MDN和Addy Osmani上找到。
Array.prototype.find(callback[, thisArg])
const arr = [1, 2, 3, 4]; const result = arr.find(elem => elem > 2); console.log(result); // Output: 3
> 提供的常見問題解答部分已經非常全面。 為了改善它,我建議:
>鞏固:結合了類似的問題(例如,關於瀏覽器兼容性的問題)。
簡潔:在保留基本信息的同時縮短答案。
:返回滿足提供的測試功能的第一個元素。
:返回第一個匹配元素的索引。
:用指定範圍內的靜態值替換數組元素。
find()
:將一系列數組元素複製到同一數組中的另一個位置。 arr.find(x => x > 5)
findIndex()
:返回數組鍵的迭代器。 arr.findIndex(x => x > 5)
fill()
arr.fill(0, 2, 4)
:從類似數組的或凹處的對象創建一個新數組。 copyWithin()
arr.copyWithin(0, 3, 4)
Q:瀏覽器兼容性和polyfills? >a:大多數現代瀏覽器支持這些方法。 但是,對於較舊的瀏覽器(尤其是Internet Explorer),您需要多填充(例如,es6-shim
)。 MDN為許多這樣的方法提供了多填充。
以上是ES6行動:新數組。* and array.protype。*方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!