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

Named array element used in function definition

最近我发现这种语法适用于 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

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

我的问题是:

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

2) 为什么 "Case 2" 有效?有没有自动转换?

正如@Xufox 指出的那样,这是因为 destructuring (array destructuring, to be more specific). Your second example works because a string is an array-like object,所以你得到 T,即 param1[0]。数字不是数组(甚至不是数组),因此引擎无法解构参数。

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

foo((123).toString()); 

正如@Xufox 正确指出的那样,这似乎是解构。

函数参数实际上可以解构:

  1. 转到https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
  2. 搜索此文本:从作为函数参数传递的对象中提取字段
  3. 现在上面显示了另一种解构的示例,示例如下:

    function userId({id}) {
      return id;
    }
    
    var user = { 
      id: 42, 
      displayName: "jdoe"
    };
    
    console.log("userId: " + userId(user)); // "userId: 42"
    

但是,我认为它也适用于此:

function foo([param1]) {
  console.log(param1);
}

此行为中整数和字符串之间的区别:

console.log('123'); //works, outputs 1, '123' = ['1', '2', '3'] of chars
console.log(['123']); //works, outputs 123
console.log([123]); //works, outputs 123
console.log(123); //error

在上面的例子中,由于字符串只不过是一个字符数组,所以它实际上可以正常工作。

正如上面那些聪明人所说的那样。计算机的读取方式如下:

foo('testParamater1') = foo(['testParamater1']);

但是...

foo(123) = foo([[1,2,3]);

不幸的是,对于您的特定用例,情况并不相同。抱歉!