【问题标题】:how to pass argument to const object variable [duplicate]如何将参数传递给const对象变量[重复]
【发布时间】:2020-07-04 09:37:51
【问题描述】:

给定

 onColumnResize(column) {

    const columnsWidth = {
        columnsWidth: {
            column: width + 'px'
        },
        detail: this.details
    };

}

如何将参数列传递给对象 columnsWidth 变量? 例如:如果参数 column = 'name',想将 'name' 传递给 column 并输出以下内容(取决于函数的参数):

onColumnResize(column) {
 const columnsWidth = {
        columnsWidth: {
            'name': width + 'px'
        },
        detail: this.details
    };
}

我的尝试: `

 onColumnResize(column) {
      const columnsWidth = {};
      columnsWidth[column] = width+'px';
      columnsWidth.detail = this.details;
  }`

除了以上方法还有其他方法吗?

【问题讨论】:

    标签: javascript ecmascript-6 constants let


    【解决方案1】:

    在您的第一个代码块中将 column 更改为 [column]

    onColumnResize(column) {
      const columnsWidth = {
        columnsWidth: {
          [column]: width + 'px'
        },
        detail: this.details
      };
    
      // ...
    }
    

    这称为computed property name,它是 ES2015 的一部分,而不是 ES2016。

    【讨论】:

    • 这可以节省我的时间。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    相关资源
    最近更新 更多