javascript - Angular 或 JS 动态变量指针名称

标签 javascript angular

我正在尝试执行以下操作。我认为这可能是不可能的,但如果是的话请分享。我试图根据 if 语句更改 this.c#,而不是一遍又一遍地编写 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#

最佳答案

  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;

关于javascript - Angular 或 JS 动态变量指针名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50533230/

相关文章:

jquery - 如何在 Webpack Angular 2 中包含 jQuery 和 Semantic-ui

javascript原型(prototype)逻辑

javascript - 第一个 child 表现不同

javascript - 导出到 excel 数据表时换行

angular - 错误类型错误 : Cannot read property 'invalid' of null Angular 8

javascript - 将数组显示为分页 View

javascript - by.css() 找到元素,但如果附加任何内容,则使用定位器找不到元素会引发错误

javascript - 添加新地址时,新添加的字段不显示验证错误

javascript - Angular 2 : check if routeName is the current one

Angular Material : Not able to drop on a dynamically created droplist