gpt4 book ai didi

javascript - 为什么函数参数在这样传入时不成为键值?

转载 作者:行者123 更新时间:2023-11-29 17:46:01 24 4
gpt4 key购买 nike

在下面的测试函数中,我传入了 2 个值并返回了一个简单的对象。由于某种原因,“cat”未用作键值,而是使用了占位符 x。我确定对此行为有明显的解释,但我看不出它是什么。也许我的大脑太困了。感谢您的帮助!

"use strict";

let functionTest = function(x, y) {
return console.log({x: y});
}

functionTest('cat', 153);

我尝试了一个箭头函数,结果是一样的。

"use strict";

let functionTest = (x, y) => console.log({x: y});

functionTest('cat', 153);

最佳答案

你必须用 [] 包裹这个值

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);

文档:Computed property names

关于javascript - 为什么函数参数在这样传入时不成为键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49684985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com