javascript modify key name

const key = 'name'
const tempObj = {key: 'shiyuq'}
console.log(tempObj)
// {key: 'shiyuq'}
// but I want a object like this  {name: 'shiyuq'}
// Finally I find a new way to modify object's key value,code follows like this:
const tempObj = {[key]: 'shiyuq'}
console.log(tempObj)
// {name: shiyuq'}

what does [ ] mean and how does it work here?
thanks!!

阅读 1.7k
2 个回答

这是 ES6 里的计算属性(Computed property names)。

等效于:

const key = 'name';
const tempObj = {};
tempObj[key] = 'shiyuq';

等效于:

const tempObj = {};
tempObj['name'] = 'shiyuq';

等效于:

const tempObj = {};
tempObj.name = 'shiyuq';
https://developer.mozilla.org...
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题