简体   繁体   English

为什么这样传递函数参数不成为键值?

[英]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.

相关问题 为什么在调用函数时无法正确传递参数? - Why the parameter can't be passed properly when function called? 为什么在传递匿名函数时`appendChild` 不能按预期工作? - Why doesn't `appendChild` work as expected when passed an anonymous function? 当console.log作为参数传递时,它起作用,但是当array.push被传递参数时,它不起作用,为什么? - When console.log passed as a parameter it works, but when array.push is passed a parameter it doesn't work why? 将参数传递给函数,参数不会变为变量 - pass argument to function, parameter doesn't become variable 为什么通过在输入上调用 function 使用 if 语句,值不会变为 false? - Why doesn't a value become false using an if statement by calling a function on input? 将console.log作为参数传递给forEach时为什么不起作用? - Why doesn't console.log work when passed as a parameter to forEach? 为什么选择单选按钮时不会禁用文本区域 - Why doesn't the textarea become disabled when choosing radio button 为什么{key:value} [“key”]不起作用? - why {key:value}[“key”] doesn't work? 为什么我在运行此函数时更改了作为参数传递的变量的值? - Why I change the value of variable which I passed as parameter when I run this function? 为什么从绑定函数返回的`this`不能严格等于传递的原始值? - Why doesn't `this` returned from bound function strictly equal passed primitive value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM