Angular或JS动态变量指针名称

时间:2018-05-25 16:14:29

标签: javascript angular

我正在尝试执行以下操作。我认为这可能是不可能的,但如果是这样,请分享。我试图改变this.c#基于if语句与写入data.filter一次超过3次。

if (chart === 'c1') {
        currentChart = this.c1;
      } else if (chart === 'c2') {
        currentChart = this.c2;
      } else if (chart === 'c3') {
        currentChart = this.c3;
      }
      currentChart = data.filter(o => {

这样的事情。 问题是没有将指针重新分配给data.filter。但是插入this.c#= data.filter,它指向this.c#

1 个答案:

答案 0 :(得分:2)

  if (chart === 'c1') {
    currentChart = this.c1;
  } else if (chart === 'c2') {
    currentChart = this.c2;
  } else if (chart === 'c3') {
    currentChart = this.c3;
  }

可以替换为

currentChart = this[chart];

或更安全:

currentChart = ['c1', 'c2', 'c3'].includes(chart) ? this[chart] : null;