好消息ECMAScript2023将新增的9个数组方法
大家好,我是 Echa。
最近小编给老铁们分享了很多关于JS相关的知识,咱们一起先回顾一下,有兴趣的小伙伴们也可以看看:
推荐17个Javascript网络请求和动画库工具类
推荐15个Javascript常用工具类
推荐Github排名前20的JavaScript开源项目
推荐19个Github热门的TypeScript学习宝库及项目
56个JavaScript 实用工具函数助你提升开发效率
ECMAScript 规范每年都会更新一次,正式标准化 JavaScript 语言的 ECMAScript 的下一次年度更新将在 2023 年 6 月左右获得批准,这将是 ECMAScript 的第 14 版。
所以在 2023 年 3 月之前达到阶段 4 的提案都将包含在 ECMAScript 2023 标准中。 对于一个提案,从提出到最后被纳入 ECMAScript 标准,总共分为五步: stage0(strawman) :任何TC39的成员都可以提交。stage1(proposal) :进入此阶段就意味着这一提案被认为是正式的了,需要对此提案的场景与API进行详尽的描述。stage2(draft) :演进到这一阶段的提案如果能最终进入到标准,那么在之后的阶段都不会有太大的变化,因为理论上只接受增量修改。state3(candidate) :这一阶段的提案只有在遇到了重大问题才会修改,规范文档需要被全面的完成。state4(finished) :这一阶段的提案将会被纳入到ES每年发布的规范之中。
根据 Erick Wendel (微软 MVP、谷歌开发专家、@nodejs合作者)的预测,ECMAScript 2023 可能会新增以下数组方法( 3️⃣、4️⃣为 所处提案阶段):3️⃣ Array.prototype.toReversed() 3️⃣ Array.prototype.toSorted() 3️⃣ Array.prototype.toSpliced() 3️⃣ Array.prototype.with() 3️⃣ Array.prototype.group() 3️⃣ Array.prototype.groupToMap() 4️⃣ Array.prototype.findLast() 4️⃣ Array.prototype.findLastIndex() 3️⃣ Array.fromAsync()
下面就来看看这些方法是如何使用的吧! 1. 通过副本更改数组
通过副本更改数组的提案目前处于第 3 阶段。该提案为数组和类型化数组提出了四种新的方法: Array.prototype.toReversed() Array.prototype.toSorted() Array.prototype.toSpliced() Array.prototype.with()
提案地址 :https://github.com/tc39/proposal-change-array-by-copy
为什么会有这个提案呢?我们知道,大多数的数组方法都是非破坏性的,也就是说,在数组执行该方法时,不会改变原数组,比如 filter() 方法:const arr = ["a", "b", "b", "a"]; const result = arr.filter(x => x !== "b"); console.log(result); // ["a", "a"]
当然,也有一些是破坏性的方法,它们在执行时会改变原数组,比如 sort() 方法:const arr = ["c", "a", "b"]; const result = arr.sort(); console.log(result); // ["a", "b", "c"]
在数组的方法中,下面的方法是具有破坏性的: reverse() sort() splice()
如果我们想要这些数组方法应用于数组而不改变它,可以使用下面任意一种形式: const sorted1 = arr.slice().sort(); const sorted2 = [...arr].sort(); const sorted3 = Array.from(arr).sort();
可以看到,我们首先需要创建数组的副本,再对这个副本进行修改。
因此改提案就引入了这三个方法的非破坏性版本,因此不需要手动创建副本再进行操作: reverse() 的非破坏性版本:toReversed() sort() 非破坏性版本:toSorted(compareFn) splice() 非破坏性版本:toSpliced(start, deleteCount, ...items)
该提案将这些函数属性引入到 Array.prototype :Array.prototype.toReversed() -> Array Array.prototype.toSorted(compareFn) -> Array Array.prototype.toSpliced(start, deleteCount, ...items) -> Array Array.prototype.with(index, value) -> Array
除此之外,该提案还还提出了一个新的非破坏性方法: with() 。该方法会以非破坏性的方式替换给定 index 处的数组元素,即 arr[index]=value 的非破坏性版本。
所有这些方法都将保持目标数组不变,并返回它的副本并执行更改。这些方法适用于数组,也适用于类型化数组,即以下类的实例: Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array BigInt64Array BigUint64Array TypedArray是一种通用的固定长度缓冲区类型,允许读取缓冲区中的二进制数据。其在WEBGL规范中被引入用于解决Javascript处理二进制数据的问题。类型化数组也是数组,只不过其元素被设置为特定类型的值。
类型化数组的核心就是一个名为 ArrayBuffer 的类型。每个ArrayBuffer对象表示的只是内存中指定的字节数,但不会指定这些字节用于保存什么类型的数据。通过ArrayBuffer能做的就是为了将来使用而分配一定数量的字节。
这些提案也适用于元组,元组相当于不可变的数组。它们拥有数组的所有方法——除了破坏性的方法。因此,将后者的非破坏性版本添加到数组对元组是有帮助的,这意味着我们可以使用相同的方法来非破坏性地更改数组和元组。 (1)Array.prototype.toReversed()
toReversed() 是 reverse() 方法的非破坏性版本:const arr = ["a", "b", "c"]; const result = arr.toReversed(); console.log(result); // ["c", "b", "a"] console.log(arr); // ["a", "b", "c"]
下面是 toReversed() 方法的一个简单的 polyfill:if (!Array.prototype.toReversed) { Array.prototype.toReversed = function () { return this.slice().reverse(); }; } (2)Array.prototype.toSorted()
toSorted() 是 sort() 方法的非破坏性版本:const arr = ["c", "a", "b"]; const result = arr.toSorted(); console.log(result); // ["a", "b", "c"] console.log(arr); // ["c", "a", "b"]
下面是 toSorted() 方法的一个简单的 polyfill:if (!Array.prototype.toSorted) { Array.prototype.toSorted = function (compareFn) { return this.slice().sort(compareFn); }; } (3)Array.prototype.toSpliced()
splice() 方法比其他几种方法都复杂,其使用形式:splice(start, deleteCount, ...items) 。该方法会从从 start 索引处开始删除 deleteCount 个元素,然后在 start 索引处开始插入item 中的元素,最后返回已经删除的元素。
toSpliced 是 splice() 方法的非破坏性版本,它会返回更新后的数组,原数组不会变化,并且我们无法再得到已经删除的元素:const arr = ["a", "b", "c", "d"]; const result = arr.toSpliced(1, 2, "X"); console.log(result); // ["a", "X", "d"] console.log(arr); // ["a", "b", "c", "d"]
下面是 toSpliced() 方法的一个简单的 polyfill:if (!Array.prototype.toSpliced) { Array.prototype.toSpliced = function (start, deleteCount, ...items) { const copy = this.slice(); copy.splice(start, deleteCount, ...items); return copy; }; } (4)Array.prototype.with()
with() 方法的使用形式:with(index, value) ,它是 arr[index] = value 的非破坏性版本。const arr = ["a", "b", "c"]; const result = arr.with(1, "X"); console.log(result); // ["a", "X", "c"] console.log(arr); // ["a", "b", "c"]
下面是 with() 方法的一个简单的 polyfill:if (!Array.prototype.with) { Array.prototype.with = function (index, value) { const copy = this.slice(); copy[index] = value; return copy; }; } 2. 数组分组(1)概述
在日常开发中,数组分组是一种极其常见的操作。因此,proposal-array-grouping 提案就提出了两个新的数组方法: array.group(callback, thisArg?) array.groupToMap(callback, thisArg?)
提案地址 :https://github.com/tc39/proposal-array-grouping
下面是这两个方法的类型签名: Array.prototype.group( callback: (value: Elem, index: number, array: Array) => GroupKey, thisArg?: any ): {[k: GroupKey]: Array} Array.prototype.groupToMap( callback: (value: Elem, index: number, array: Array) => GroupKey, thisArg?: any ): Map>
这两个方法都用来对数组进行分组: 输入:一个数组; 输出:组,每个组都有一个组key,以及一个包含组成员的数组。
这两个方法都会对数组进行遍历,它们会向其回调请求组键并将元素添加到相应的组中。这两个方法在表示组的方式上有所不同: group() :将组存储在对象中:组键存储为属性键,组成员存储为属性值;groupToMap() :将组存储在 Map 中:组键存储为 Map 键,组成员存储为 Map 值。
那这两个方法该如何选择呢?我们知道,JavaScript 中对象是支持解构的,如果想要使用解构来获取数组中的值,比如,对于上面对象,可以通过解构获取三个不同组的值: const {vegetables, fruit, meat} = result;
而 Map 的好处就是它的 key 不限于字符串和symbol ,更加自由。(2)使用
下面来看几个实用例子。假如执行 Promise.allSettled() 方法返回的数组如下:const settled = [ { status: "rejected", reason: "Jhon" }, { status: "fulfilled", value: "Jane" }, { status: "fulfilled", value: "John" }, { status: "rejected", reason: "Jaen" }, { status: "rejected", reason: "Jnoh" }, ]; const {fulfilled, rejected} = settled.group(x => x.status); // fulfilled 结果如下: [ { status: "fulfilled", value: "Jane" }, { status: "fulfilled", value: "John" }, ] // rejected 结果如下: [ { status: "rejected", reason: "Jhon" }, { status: "rejected", reason: "Jaen" }, { status: "rejected", reason: "Jnoh" }, ]
在这个例子中,使用 group() 的效果会更好,因为可以使用解构轻松获取需要组的值。
假如想要对以下数组中人根据国家进行分组: const persons = [ { name: "Louise", country: "France" }, { name: "Felix", country: "Germany" }, { name: "Ava", country: "USA" }, { name: "Léo", country: "France" }, { name: "Oliver", country: "USA" }, { name: "Leni", country: "Germany" }, ]; const result = persons.groupToMap((person) => person.country); // result 的执行结果和以下 Map 是等价的: new Map([ [ "France", [ { name: "Louise", country: "France" }, { name: "Léo", country: "France" }, ] ], [ "Germany", [ { name: "Felix", country: "Germany" }, { name: "Leni", country: "Germany" }, ] ], [ "USA", [ { name: "Ava", country: "USA" }, { name: "Oliver", country: "USA" }, ] ], ])
在这个例子中, groupToMap() 是更好的选择,因为我们可以在Map 中使用任何类型的键,而在对象中,键只能是字符串或symbol 。(3)polyfill
下面来实现一下这两个方法: Array.prototype.group Array.prototype.group = function (callback, thisArg) { const result = Object.create(null); for (const [index, elem] of this.entries()) { const groupKey = callback.call(thisArg, elem, index, this); if (! (groupKey in result)) { result[groupKey] = []; } result[groupKey].push(elem); } return result; }; Array.prototype.groupToMap Array.prototype.groupToMap = function (callback, thisArg) { const result = new Map(); for (const [index, elem] of this.entries()) { const groupKey = callback.call(thisArg, elem, index, this); let group = result.get(groupKey); if (group === undefined) { group = []; result.set(groupKey, group); } group.push(elem); } return result; }; 3. 从尾到头搜索数组(1)概述
在 JavaScript 中,通过 find() 和 findIndex() 查找数组中的值是一种常见做法。不过,这些方法从数组的开始进行遍历:const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}]; array.find(elem => elem.v > 3); // {v: 4} array.findIndex(elem => elem.v > 3); // 3
如果要从数组的末尾开始遍历,就必须反转数组并使用上述方法。这样做就需要一个额外的数组操作。幸运的是,Wenlu Wang 和 Daniel Rosenwasser 关于 findLast() 和 findLastIndex() 的 ECMAScript 提案解决了这一问题。该提案的一个重要原因就是:语义。
提案地址:https://github.com/tc39/proposal-array-find-from-last (2)使用
它们的用法和 find() 、findIndex() 类似,唯一不同的是它们是 从后向前 遍历数组,这两个方法适用于数组和类数组。findLast() 会返回第一个查找到的元素,如果没有找到,就会返回 undefined ;findLastIndex() 会返回第一个查找到的元素的索引。如果没有找到,就会返回 -1;const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}]; array.findLast(elem => elem.v > 3); // {v: 5} array.findLastIndex(elem => elem.v > 3); // 4 array.findLastIndex(elem => elem.v > 5); // undefined (3)polyfill
下面来实现一下这两个方法: Array.prototype.findLast Array.prototype.findLast = function(arr, callback, thisArg) { for (let index = arr.length - 1; index >= 0; index--) { const value = arr[index]; if (callback.call(thisArg, value, index, arr)) { return value; } } return undefined; } Array.prototype.findLastIndex Array.prototype.findLastIndex = function(arr, callback, thisArg) { for (let index = arr.length - 1; index >= 0; index--) { const value = arr[index]; if (callback.call(thisArg, value, index, arr)) { return index; } } return -1; } (4)参考源码
lodash 中也提供了类似方法,下面是相关源码: findLast() import findLastIndex from "./findLastIndex.js" import isArrayLike from "./isArrayLike.js" /** * This method is like `find` except that it iterates over elements of * `collection` from right to left. * * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @see find, findIndex, findKey, findLastIndex, findLastKey * @example * * findLast([1, 2, 3, 4], n => n % 2 == 1) * // => 3 */ function findLast(collection, predicate, fromIndex) { let iteratee const iterable = Object(collection) if (!isArrayLike(collection)) { collection = Object.keys(collection) iteratee = predicate predicate = (key) => iteratee(iterable[key], key, iterable) } const index = findLastIndex(collection, predicate, fromIndex) return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined } export default findLast findLastIndex() import baseFindIndex from "./.internal/baseFindIndex.js" import toInteger from "./toInteger.js" /** * This method is like `findIndex` except that it iterates over elements * of `collection` from right to left. * * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @see find, findIndex, findKey, findLast, findLastKey * @example * * const users = [ * { "user": "barney", "active": true }, * { "user": "fred", "active": false }, * { "user": "pebbles", "active": false } * ] * * findLastIndex(users, ({ user }) => user == "pebbles") * // => 2 */ function findLastIndex(array, predicate, fromIndex) { const length = array == null ? 0 : array.length if (!length) { return -1 } let index = length - 1 if (fromIndex !== undefined) { index = toInteger(fromIndex) index = fromIndex < 0 ? Math.max(length + index, 0) : Math.min(index, length - 1) } return baseFindIndex(array, predicate, index, true) } export default findLastIndex 4. Array.fromAsync
在 JavaScript 中内置了 Array.from 方法,它用于将类数组或者可迭代对象生成一个新的数组实例。在ECMAScript 2018中引入了异步可迭代对象。而JavaScript中一直缺少直接从异步可迭代对象生成数组的内置方法。
proposal-array-from-async 提案中提出来的 Array.fromAsync 方法就是为了解决这个问题而提出来的。
下面来看一个简单的例子: async function * asyncGen (n) { for (let i = 0; i < n; i++) yield i * 2; } // arr 将变为 [0, 2, 4, 6]` const arr = []; for await (const v of asyncGen(4)) { arr.push(v); } // 与上述方式是等价的 const arr = await Array.fromAsync(asyncGen(4));
Array.fromAsync 可以将异步迭代转换为 promise ,并将解析为新数组。在 promise 解析之前,它将从输入值中创建一个异步迭代器,进行惰性的迭代,并将每个产生的值添加到新数组中。
与其他基于 Promise 的 API 一样, Array.fromAsync 总是会立即返回一个 promise 。当 Array.fromAsync 的输入在创建其异步或同步迭代器时引发错误时,则此 promise 状态将被置为 rejected 。
提案地址:https://github.com/tc39/proposal-array-from-async
准妈妈孕中查出宫颈癌,冒险挺过放疗后顺利产子极目新闻记者刘迅通讯员聂文闻彭锦弦欣喜怀上老二,却因一次出血意外查出宫颈癌。在医生都劝她放弃生子时,36岁的准妈妈艰难抉择,仍想保住腹中宝宝。在武汉协和医院多学科专家守护下,11月
3岁精选4本绘本,每本都喜欢(二)话不多说,先上这期要分享的3岁绘本小清单,不多,但每本都好有意思啊。02hr亚历山大和发条老鼠著绘美李欧李奥尼适读年龄3岁对李欧李奥尼的经典绘本系列,我表示很偏爱,恨不得一一介绍。
婴儿出生时体重多少斤比较好?5斤6斤8斤,有什么区别?儿媳妈,我不想喝了,我吃饱了。吃太多长太胖了,对宝宝不好,到时候我怕不好生。婆婆瞎说!你吃好了,补充营养,宝宝才能长得好啊。儿媳补充营养没错,我有在补,但不能总喝这种鸡汤的,不仅补
印度智能手机市场Q3下滑IT之家11月7日消息,CounterpointResearch公布了印度智能手机市场的季度分析。2022年第三季度数据显示,全年销量总体下降11,降至4500万部。这是印度7月至
6元一斤的散装白酒真的不能喝了吗?建议先了解风险,再喝不迟6元一斤的散装白酒真的不能喝了吗?建议先了解风险,再喝不迟有时候想想挺有意思的,人的收入有高有低,酒的价格也有贵有便宜。高档的真的不少,但散装酒似乎更受欢迎。说到底还是这个社会上的
纯电续航1008km,28。66万的起步价,AIONLXPLUS抢高端市场近期埃安发布了一款新车型,它就是AIONLXPLUS,作为改款车型,新车在设计上做了改进,配置上也有所变动,最吸引人的当属续航,最高可以达到1008公里,完美解决了用户的续航忧虑症
从无人机跨界智能驾驶,大疆凭什么搅动市场?(观察者网讯文周昊编辑庄怡)一套前视双目摄像头,4个环视鱼眼摄像头,1颗前向毫米波雷达,12颗超声波雷达这些总价甚至不如一颗高精激光雷达贵的硬件设备,却可以在智能驾驶领域实现包括打
八部门到2025年,户外运动产业总规模超过3万亿元近日,体育总局发展改革委等八部门联合印发户外运动产业发展规划(20222025年)(以下简称规划)的通知提出,到2025年,户外运动场地设施持续增加,普及程度大幅提升,参与人数不断
李锋上下游协同促光伏产业提质来源经济日报日前,国家发展改革委办公厅国家能源局综合司联合发布关于促进光伏产业链健康发展有关事项的通知,意在引导光伏产业上下游协同发展,多维度多举措纾解光伏产业链上下游产能价格堵点
绿色低碳循环现代产业园在湛江东海岛加速崛起湛江东海岛是湛江经济技术开发区(以下称湛江经开区)产业发展的主要载体,湛江工业发展的主战场,广东省最大的临港工业岛,也是宝钢湛江钢铁中科炼化巴斯夫等投资超百亿美元的巨无霸项目所在地
预防干眼症的小妙招干眼症是生活中很常见的一种眼科疾病,引起干眼症的病因有很多,干眼症如果不及时的进行治疗带来的危害是很大的,对于这种疾病应该及时的做好预防措施。下面就带大家了解一下干眼症的预防措施,