简体   繁体   中英

how to use a string assigned to a variable as an object key

Using a variable for a key in a JavaScript object literal

I am started learning javascript and have seen the answer(below) for the above question but

var thetop = "top",
obj = { [thetop]: 10 };                                 
console.log(obj.top); 

what if i have

var date = new Date().getDate(); 
var value= String(date); 
obj ={[value]:100};
console.log(obj.value);

I did not find the answer for the above code .As the variable value changes everyday i want to use value while using console.log(obj.value) not the actual date. Can someone tell me how to do it .

You can read the value property with "[]" instead of ".", like this:

 var date = new Date().getDate(); var value= String(date); obj ={[value]:100}; console.log(obj[value]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM