>本文探讨了几种新的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中文网其他相关文章!