首页 > 解决方案 > Javascript Class:实例化类时的getter值

问题描述

我有一个快速的问题——在 Hacker Rank 中是个挑战——试图找到答案。

问题是这样的。

控制台日志应该打印类中数字的相反顺序。限制: 1. 类构造函数不能修改。2. 不得修改控制台日志语句。

你可以做任何其他事情来让它工作。

class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line 
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2

只是想知道我们如何实现这一点?

标签: javascriptecmascript-6

解决方案


使用符号迭代器是众多方法之一

class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }
  [Symbol.iterator]() {
    return this.numbers.reverse().values()
  }
  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line 
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2


推荐阅读