Javascript-如何从对象构造函数中的字典中检索密钥
目前,我正在初始化一个对象,它的一个值是从字典中检索的,简化形式如下Javascript-如何从对象构造函数中的字典中检索密钥,javascript,dictionary,constructor,key-value,Javascript,Dictionary,Constructor,Key Value,目前,我正在初始化一个对象,它的一个值是从字典中检索的,简化形式如下 var TrailColor = { red: '#FF0000', orange: '#FF9900', yellow: '#FFFF00' }; function Trail(trailName, trailColor) { this.trailName = trailName; this.trailColor = trailColor; } var trail1 = new
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);
现在我已经决定,我不仅想要颜色代码,还想要颜色名称作为这个对象的一部分。但是,我不确定如何“反向”检索颜色名称,因此我根据值获取一个精确的键(不是整个数组,我知道如何获取),并将其作为对象的属性。是否有一些简单的方法可以做到这一点,而不需要遍历整个数组?多谢各位 我会首先传递颜色名称而不是值:
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"
因此,传入“red”并读取Trail中的颜色……换句话说,将
red
作为字符串传入,然后Trail()
获取名称并可以使用该名称执行字典查找。