首页 > 解决方案 > 访问有序的类属性

问题描述

我对编码真的很陌生,希望得到一些帮助来解决这个问题:我想以某种有序的方式访问我的类中的对象,直到我访问前三个。我以为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));在行

标签: javascript

解决方案


推荐阅读