在PHP中,我们有一个简洁的use
关键字,允许在使用闭包时使用"外部"变量,如下所示:
$tax = 10;
$totalPrice = function ($quantity, $price) use ($tax){ //mandatory 'use'
return ($price * $quantity) * ($tax + 1.0);
};
Run Code Online (Sandbox Code Playgroud)
如果我们省略该use ($tax)
部分,它将抛出一个错误,我非常喜欢.
类似地,在C++ 11中,我们也这样做,使用括号指定称为捕获列表的外部变量:
float tax = 10;
auto totalPrice = [tax](int quantity, float price){ //mandatory []
return (price*quantity) * (tax + 1.0);
};
Run Code Online (Sandbox Code Playgroud)
与在php中一样,如果省略捕获列表,则会抛出错误.
在Javascript中,我们没有等效于此use
关键字(或c ++ []),我们只是这样做:
var tax = 10;
var totalPrice = function (quantity, price){ //no need for 'use' or similar
return (price * quantity) * (tax …
Run Code Online (Sandbox Code Playgroud) 我尝试创建一个具有最后一个键值的对象.我只有一个带有键和值的数组但不知道如何在javascript中不使用引用来创建对象.
据我所知,没有办法在javascript中创建变量的引用.
这就是我所拥有的:
var value = 'test';
var keys = ['this', 'is', 'a', 'test'];
Run Code Online (Sandbox Code Playgroud)
这就是我要的:
myObject: {
this : {
is: {
a : {
test : 'test'
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
知道我怎么能用JavaScript做到最好吗?