码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-08-09 21:24:58      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:pre   property   对象   following   http   hat   use   win   www   

{ 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如何使用变量设置对象的键名 /

标签:pre   property   对象   following   http   hat   use   win   www   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!