javascript - 访问有序的类属性
问题描述
我对编码真的很陌生,希望得到一些帮助来解决这个问题:我想以某种有序的方式访问我的类中的对象,直到我访问前三个。我以为this[1]
可能意味着this.x
,但我发现它不能:
class TargetingSolution{
constructor(config){
this.x = config.x
this.y = config.y
this.z = config.z
this.solution = [];
}
target (){
for (var i = 0; i < 3; i++){
this.solution.push(this[i])
}
}
}
// The following lines of code are not required for the solution, but can be
// used by you to test your solution.
const m = new TargetingSolution({
x: 10,
y: 15,
z: 900
});
console.log(m.target()); // would print "(10, 15, 900)"
所以我在尝试了很多不同的东西几个小时后在这里找到了这个解决方案
class TargetingSolution{
constructor(config){
this.x = config.x
this.y = config.y
this.z = config.z
this.solution = [];
}
target (){
for (var a in this) {
if(a === 'x' | a === 'y' | a === 'z'){
this.solution.push(this[a])
}
else{
break
}
}
return this.solution;
}
}
// The following lines of code are not required for the solution, but can be
// used by you to test your solution.
const m = new TargetingSolution({
x: 10,
y: 15,
z: 900
});
console.log(m.target()); // would print "(10, 15, 900)"
但我想知道是否有更聪明(但更简单)的方法来做到这一点。
我尝试过的另一个例子是:
class TargetingSolution{
constructor(config){
this.x = config.x
this.y = config.y
this.z = config.z
this.solution = [];
}
target (){
return config.forEach(element => this.solution.push(element));
}
}
// The following lines of code are not required for the solution, but can be
// used by you to test your solution.
const m = new TargetingSolution({
x: 10,
y: 15,
z: 900
});
console.log(m.target()); // would print "(10, 15, 900)"
(但它不起作用,config
因为
return config.forEach(element => this.solution.push(element));
在行
解决方案
推荐阅读
- reactjs - 如何将用户重定向到不同的页面?
- google-sheets-api - 从 Google Sheet 读取连接只允许前 100,000 行
- java - AnnotatedConnectException - Springboot - 微服务 - 使用 eureka 服务器的分布式服务器
- sql - 如何对特定列分组的列求和?
- android - 如何在 RecyclerView 中对字符串元素进行排序?
- jquery - jQuery AJAX - 将响应 HTML 显示为页面
- sql - SQL,从具有不同属性但另一个属性的最大值的行中选择值
- android-ndk - lldb 无法显示来源
- java - 将 JavaFX 打包到可执行的胖 JAR 中,但 Maven 不会生成有效的类路径
- flutter - 带有数学运算符的颤振键盘