【问题标题】:Javascript - how to retrieve a key from dictionary in the Object constructorJavascript - 如何在 Object 构造函数中从字典中检索键
【发布时间】:2018-10-22 20:38:18
【问题描述】:

目前,我正在初始化一个对象,它的一个值是从字典中检索到的,以类似这样的简化形式

var TrailColor = {
    red: '#FF0000',
    orange: '#FF9900',
    yellow: '#FFFF00' 
};

function Trail(trailName, trailColor) {
    this.trailName = trailName;
    this.trailColor = trailColor;
}

var trail1 = new Trail("TrailName", TrailColor.red);

现在我已经决定,我想要的不仅是颜色代码,还有颜色名称作为这个对象的一部分。但是,我不确定如何“反向”检索颜色名称 - 所以我根据值获取一个确切的键(不是整个数组,我知道如何获取它)并将其作为对象的属性。是否有一些直接的方法可以做到这一点,而无需遍历整个数组?谢谢你。

【问题讨论】:

  • 所以传入“红色”并读取 Trail 内的颜色....
  • red 作为字符串 传入,换句话说,Trail() 获取名称并可以使用它来执行字典查找。

标签: javascript dictionary constructor key-value


【解决方案1】:

我会首先传递颜色名称而不是值:

function Trail(name, color = 'red') {
  this.name = name;
  this.colorName = color;
  this.color = this._colors[color];
}

Object.assign(Trail.prototype, {
  _colors: {
    red: '#FF0000',
    orange: '#FF9900',
    yellow: '#FFFF00'
  },
  getColorName() {
    return this.colorName;
  }
});

const trail = new Trail("TrailName", "red");
trail.colorName // => "red"
trail.getColorName() // => "red"     
trail.color // => "#FF0000" 

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 2019-01-06
    • 1970-01-01
    • 2018-03-22
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多