在调用函数时不熟悉使用方括号 [英] Unfamiliar use of square brackets in calling a function
本文介绍了在调用函数时不熟悉使用方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在页面的中间,我找到了以下代码。
In the middle of this page, I find the code below.
var plus = function(x,y){ return x + y };
var minus = function(x,y){ return x - y };
var operations = {
'+': plus,
'-': minus
};
var calculate = function(x, y, operation){
return operations[operation](x, y);
}
calculate(38, 4, '+');
calculate(47, 3, '-');
现在虽然我可以追踪它是如何工作的,但我以前从未见过使用方括号。它当然看起来不像创建数组或引用数组的成员。这是常见的吗?如果是这样,其他一些例子在哪里?
Now while I can trace how it works, I've never seen this use of square brackets before. It certainly doesn't look like it's creating an array or referencing a member of an array. Is this common? If so, where are some other examples?
推荐答案
这是一个字典访问,就像一个数组,但带有一个键而不是数字索引。
It is a dictionary access, which is like an array, but with a key instead of a numeric index.
operations ['+']
将评估函数 plus
,然后使用参数 plus(x,y)
调用。
operations['+']
will evaluate to the function plus
, which is then called with the arguments plus(x,y)
.
这篇关于在调用函数时不熟悉使用方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文