小编Edg*_*ado的帖子

闭包:用Javascript或者翻译语言中的PHP"use"关键字或C++捕获列表的等价物

在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 php closures c++11 typescript

11
推荐指数
1
解决办法
1105
查看次数

Javascript按数组创建Object

我尝试创建一个具有最后一个键值的对象.我只有一个带有键和值的数组但不知道如何在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做到最好吗?

javascript arrays recursion object

1
推荐指数
1
解决办法
117
查看次数

标签 统计

javascript ×2

arrays ×1

c++11 ×1

closures ×1

object ×1

php ×1

recursion ×1

typescript ×1