首页 > 解决方案 > 请帮我弄清楚 Array concat() 方法并编写纯 Javascript 代码

问题描述

请帮我弄清楚 Array concat() 方法并编写纯 Javascript 代码。这是来自 ECMA-262 标准的代码

  1. 让 O 成为 ? ToObject(此值)。
  2. 让 A 成为 ? ArraySpeciesCreate(O, 0)。
  3. 令 n 为 0。
  4. 让 items 是一个 List,其第一个元素是 O,其后续元素按从左到右的顺序是传递给此函数调用的参数。
  5. 重复,而项目不为空

    一个。从 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.
    
  6. 履行 ?设置(A,“长度”“长度”,n,真)。
  7. 返回 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()一样接收效果

标签: javascript

解决方案


关于你在评论中的问题。您可以通过调用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']);


推荐阅读