首页 > 编程语言 > 详细

JavaScript如何使用变量设置对象的键名 /

时间:2017-08-09 20:37:42      阅读:177      评论:0      收藏:0      [点我收藏+]
{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:

obj = { thetop : 10 };
obj = { "thetop" : 10 };

In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:

var thetop = "top";

// create the object literal
var aniArgs = {};

// Assign the variable property name with a value of 10
aniArgs[thetop] = 10; 

ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:

var thetop = "top",
    obj = { [thetop]: 10 };

console.log(obj.top); // -> 10

chrome测试:


ES5

 

 

https://www.douban.com/note/625698916/

JavaScript如何使用变量设置对象的键名 /

原文:http://www.cnblogs.com/xfdmb/p/7327415.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!