简体   繁体   English

改变对象的价值

[英]Alter value in object

Writing Javascript, I have an object/class with the following attributes: 在编写Javascript时,我有一个具有以下属性的对象/类:

this.option1Active = null;
this.option2Active = null;
this.option3Active = null;
this.option4Active = null;

I would like to set one of those attributes to true based on the parameter genre 我想根据参数genre将这些属性之一设置为true

function selectGenre (genre) {
  if (genre === 'option1') {
    this.option1Active = true;
  }

  else if (genre === 'option2') {
    this.option2Active = true;
  }

  else if (genre === 'option3') {
    this.option3Active = true;
  }

  else if (genre === 'option4') {
    this.option4Active = true;
  }
}

Though writing if statements is not a sustainable solution. 尽管编写if语句不是可持续的解决方案。 I'd like to do something like this: 我想做这样的事情:

function selectGenre (genre) {
  var options = {
    'option1': this.option1Active,
    'option2': this.option2Active,
    'option3': this.option3Active,
    'option4': this.option4Active
  };

  options[genre] = true;
}

But that only set options[index] to true, not eg this.option1Active . 但这仅将options[index]设置为true,而不是this.option1Active Is there a way to change the reference a key of an object points to? 有没有一种方法可以更改对象键指向的引用?

If not, other ways of refactoring the if statements is greatly appreciated. 如果不是,则非常感谢重构if语句的其他方法。

You can use a string for the property name to set on this . 您可以使用字符串作为属性名称在this设置。

var genreOptions = {
  'option1': 'option1Active',
  'option2': 'option2Active',
  'option3': 'option3Active',
  'option4': 'option4Active'
};

function selectGenre (genre) {
  this[genreOptions[genre]] = true;
}

It seems you can just append "Active" to genre to get the property itself: 似乎您可以仅在genre上附加"Active" ,以获取属性本身:

function selectGenre (genre) 
{
  var prop = genre + 'Active';

  if (typeof this[prop] != 'undefined') {
      this[prop] = true;
  }
}

Though, it would be easier if you could use an array as your property instead, ie this.optionActive[3] vs. this.option3Active . 不过,如果您可以使用数组作为属性( this.optionActive[3]this.option3Active ,则会更容易。

Is this what you want ? 这是你想要的吗 ?

var obj = {};
obj.option1Active = null;
obj.option2Active = null;
obj.option3Active = null;
obj.option4Active = null;

var options = {
    option1: 'option1Active',
    option2: 'option2Active',
    option3: 'option3Active',
    option4: 'option4Active'
};

function selectGenre(genre) {
    obj[options[genre]] = true;
}

console.log(obj);
selectGenre('option2');
console.log(obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM