第十四篇 如何实现数组 push、pop 方法 ?
参照 ecma262 草案的规定,关于 push 和 pop 的规范如下图所示:
首先来实现一下 push 方法:
Array.prototype.push = function(...items) { let O = Object(this); let len = this.length >>> 0; let argCount = items.length >>> 0; // 2 ** 53 - 1 为 JS 能表示的最大正整数 if (len + argCount > 2 ** 53 - 1) { throw new TypeError("The number of array is over the max value restricted!") } for(let i = 0; i < argCount; i++) { O[len + i] = items[i]; } let newLength = len + argCount; O.length = newLength; return newLength; }
亲测已通过 MDN 上所有测试用例。MDN 链接
然后来实现 pop 方法:
Array.prototype.pop = function() { let O = Object(this); let len = this.length >>> 0; if (len === 0) { O.length = 0; return undefined; } len --; let value = O[len]; delete O[len]; O.length = len; return value; }
亲测已通过 MDN 上所有测试用例。MDN 链接
更多相关文章推荐:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 第十四篇 如何实现数组 push、pop 方法 ?
码云笔记 » 第十四篇 如何实现数组 push、pop 方法 ?