簡體   English   中英

使用 static 方法實現一個列表 javascript

[英]implement a list with a static method javascript

我必須按照以下說明重新實現一個列表和 forEach 方法:

//不要在您的解決方案中構造任何數組文字 ([])。

//不要在你的解決方案中通過 new Array 構造任何 arrays。

//不要在你的解決方案中使用任何 Array.prototype 方法。

// 您可以使用 Iterable 中的解構和擴展 (...) 語法。

結果應該是這樣的:

const list = List.create(1, 2)
list.forEach((item) => console.log(item))

這是我不完整的解決方案:

export class List {

  constuctor(){
    
  }

  public static create(...values: number[]): List {
    // Do *not* construct any array literal ([]) in your solution.
    // Do *not* construct any arrays through new Array in your solution.
    // DO *not* use any of the Array.prototype methods in your solution.

        // You may use the destructuring and spreading (...) syntax from Iterable.
        List list = new List();
        values.forEach(function(item){
          list.push(item);
        });  
        return list;
      }
    
      public forEach(callback: any){
        for (let i = 0; i<this.length ; i++){
           callback(this[i], i, this);
        }
      }
    
    }

在創建循環中,但問題是,作為 static 方法,this 無法識別

編輯感謝評論

... this不被認可

這是。 但是你沒有給this任何屬性。 這是因為:

  • constuctor應該寫成constructor
  • 您需要定義一個push方法(因為您在create中調用了它)
  • 您需要定義一個length屬性(因為您在forEach中引用了它)

此外,還有一些其他問題:

  • 你寫Array.prototype函數不能使用,但你的代碼有values.forEach() ,...所以這違反了該規則。 請改用for..of循環。

這是您的代碼,其中包含這些評論:

 class List { constructor() { this.length = 0; } push(value) { this[this.length++] = value; } static create(...values) { let list = new List(); for (let item of values) { list.push(item); } return list; } forEach(callback) { for (let i = 0; i < this.length; i++) { callback(this[i], i, this); } } } const list = List.create(1, 2) list.forEach((item) => console.log(item))

評論

上面的“測試”會很好,但是當對屬性的賦值也能正常工作時,比如list[2] = 3 ,那么還有更多事情需要處理。 以這個程序為例:

const list = List.create(1, 2);
list[5] = 42; // should update length
list.check = true; // should not update length
console.log("length = " + list.length);
console.log("enumerable keys are " + Object.keys(list));
list.forEach((item) => console.log(item)); // should not output empty slots
list.length = 1; // should delete some index properties
list.forEach((item) => console.log(item)); // should not output deleted items

...那么 output 應該是:

length = 6
enumerable keys are 0,1,5,check
1
2
42
1

您可以通過捕獲對屬性的訪問並使length成為 getter/setter 來實現這一點。 但是您還需要區分是數組索引的屬性,哪些不是,所以總而言之,這將使代碼變得不那么瑣碎。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM