[英]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. 在下面的测试函数中,我传入2个值并返回一个简单的对象。 For some reason 'cat' isn't used as the key value and instead the placeholder x is used.
由于某些原因,“ cat”不用作键值,而是使用占位符x。 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 使用
[X]
,这是ES6语法
"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.
从ECMAScript 2015开始,对象初始化程序语法还支持计算的属性名称。 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 Doc: 计算的属性名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.