简体   繁体   中英

Why doesn't function parameter become key value when passed in as such?

In the following test function I pass in 2 values and return a simple object. For some reason 'cat' isn't used as the key value and instead the placeholder x is used. I'm sure there is an obvious explanation for this behavior but I can't see what it is. Maybe my brain is just too sleepy. Thanks for any help!

 "use strict"; let functionTest = function(x, y) { return console.log({x: y}); } functionTest('cat', 153); 

I tried an arrow function and the result was the same.

 "use strict"; let functionTest = (x, y) => console.log({x: y}); functionTest('cat', 153); 

use [X] ,this is ES6 grammar

 "use strict"; let functionTest = function(x, y) { return console.log({[x]: y}); } functionTest('cat', 153); 

You have to wrap the value with []

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you might have used to read and set properties already. Now you can use a similar syntax in object literals, too:

 "use strict"; let functionTest = function(x, y) { return console.log({[x]: y}); } functionTest('cat', 153); 

Doc: Computed property names

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