简体   繁体   中英

Using function parameter value as dictionary key

Attempting to build a dictionary using key that comes via function parameter.

var progres_mark = function(progress_state) {
  var now = Date();
  console.log({ progress_state : now })
}

progres_mark("encode")

Expected

{ 'encode': 'Sun Oct 19 2014 18:22:33 GMT+0300 (IDT)' }

Actual

{ progress_state: 'Sun Oct 19 2014 18:22:33 GMT+0300 (IDT)' }

What's going on?

Because the compiler only expects an identifier or a string and therefore will not evaluate to the variable's value. But you can use bracket notation to achieve what you want.

var progres_mark = function(progress_state) {
  var now = Date();
  var obj = {}; obj[progress_state] = now;
  console.log(obj)
}

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