函数定义中使用的命名数组元素

iPa*_*h ツ 6 javascript arrays function implicit-conversion

最近我发现这种语法适用于JavaScript(Chrome 53):

function foo([param1]) { // Function argument is declared as array and param1 is used as variable? What is the name of this syntax?
  console.log(param1); 
}

foo(['TestParameter1']); // Case 1 - works. Output: TestParameter1
foo('TestParameter1');   // Case 2 - works??? Why? Output: TestParameter1
foo(123);                // Case 3 - does not work - VM860:1 Uncaught TypeError: undefined is not a function(…)

Result => TestParameter1 // this is the result
Run Code Online (Sandbox Code Playgroud)

我看到param1可以用作引用第一个参数中索引为0的项的变量(声明为数组).

我的问题是:

1)这个语法是如何命名的([param1]部分允许你使用param1作为变量)?

2)为什么"案例2"有效?有自动转换吗?

Rob*_* M. 3

正如@Xufox 指出的,这是因为destructuring(更具体地说是数组解构)。你的第二个例子之所以有效,是因为字符串是一个类似数组的对象,所以你得到T,即param1[0]。数字不是数组(甚至不是类数组),因此引擎无法解构参数。

如果你将你的号码强制转换为字符串,它将起作用:

foo((123).toString()); 
Run Code Online (Sandbox Code Playgroud)