javascript - 请帮我弄清楚 Array concat() 方法并编写纯 Javascript 代码
问题描述
请帮我弄清楚 Array concat() 方法并编写纯 Javascript 代码。这是来自 ECMA-262 标准的代码
- 让 O 成为 ? ToObject(此值)。
- 让 A 成为 ? ArraySpeciesCreate(O, 0)。
- 令 n 为 0。
- 让 items 是一个 List,其第一个元素是 O,其后续元素按从左到右的顺序是传递给此函数调用的参数。
重复,而项目不为空
一个。从 items 中删除第一个元素,让 E 成为元素的值。
湾。让可传播的吗?IsConcatSpreadable(E)。
C。如果spreadable为真,那么
i. Let k be 0. ii. Let len be ? ToLength(? Get(E, "length" "length")). iii. If n + len > 253-1, throw a TypeError exception. iv. Repeat, while k < len 1. Let P be ! ToString(k). 2. Let exists be ? HasProperty(E, P). 3. If exists is true, then a. Let subElement be ? Get(E, P). b. Perform ? CreateDataPropertyOrThrow(A, ! ToString(n), subElement). 4. Increase n by 1. 5. Increase k by 1.
d。否则 E 作为单个项目添加而不是展开,
i. If n≥253-1, throw a TypeError exception. ii. Perform ? CreateDataPropertyOrThrow(A, ! ToString(n), E). iii. Increase n by 1.
- 履行 ?设置(A,“长度”“长度”,n,真)。
- 返回 A。
我想要这样的代码。
Array.prototype.con = 函数(){
let 0 = ;
let A = ;
let n = 0;
let item = ;
so on...
}
让 arr1 = [1,2];
让 arr2 = [3,4];
arr1.con(arr2) //像concat()一样接收效果
解决方案
关于你在评论中的问题。您可以通过调用this
原型函数来访问项目。它指的是您正在调用的实际实例。
items = this;
Array.prototype.newTest = function(toBeAdded){
console.log('this', this);
console.log('To be Added', toBeAdded);
}
const arr = ['foo', 'bar'];
arr.newTest(['x','y']);
推荐阅读
- python - 当我们释放对 kivy 开关项目的点击时如何触发一个事件?
- javascript - MTN MOMO API CreateAPI 用户 - 401 访问被拒绝
- c# - 使用 TSPL/TSPL2 和 C# 获取打印机状态
- mongodb - 使用 express 和 mongodb 存储到具有单个对象数据的多个文档中
- windows - 有没有办法可以将我的外部硬盘捕获为可移动驱动器
- php - 无法对另一个 Laravel 网站执行 API 调用
- javascript - 是的,基于其他字段值的多重条件验证
- google-cloud-platform - Google Cloud AI 平台 -- 未检测到正在运行的 VM 实例
- python - 在 plotly dash 上创建条形图的问题
- typescript - Typscript 错误 2322 - 无法初始化 2 个可选索引签名的通用类型联合的常量