首页 > 解决方案 > 如何将参数传递给 const 对象变量

问题描述

给定

 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;
  }`

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

标签: javascriptecmascript-6constantslet

解决方案


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

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

  // ...
}

这称为计算属性名称,它是 ES2015 的一部分,而不是 ES2016。


推荐阅读