javascript - 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
只是想知道我们如何实现这一点?
解决方案
使用符号迭代器是众多方法之一
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
推荐阅读
- android - WifiManager startScan() 仅第一次工作
- c++ - 在 c++ 中分配像 int a[10][10] 这样的数组和使用 new 关键字分配数组有什么区别?
- xamarin - 如何证明我的 Xamarin.iOS Watch 应用已启用位码?
- c++ - 哪个 NFS 实现对于多进程访问的 sqlite 数据库是安全的
- ios - UITextView 的 RxSwift 事件
- pandas - 如何根据唯一值计数列出熊猫数据框中的列?
- swift - DispatchGroup 在 Swift 中通知“Main”
- entity-framework - Entity Framework Z Plus 批量更新
- reporting-services - BigQuery 报告/BI 工具的建议
- spring-boot - Spring Data Cassandra 分页