且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript 通过变量设置对象键

更新时间:2023-01-17 15:21:56

需要先制作对象,然后使用[]设置.

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};

obj[key] = someValueArray;
myArray.push(obj);


2021 年更新:


UPDATE 2021:

计算属性名称功能是在 ECMAScript 2015 (ES6) 中引入的,它允许您以 JavaScript 对象文字表示法动态计算对象属性的名称.

Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.

const yourKeyVariable = "happyCount";
const someValueArray= [...];

const obj = {
    [yourKeyVariable]: someValueArray,
}