2016-10-03 96 views
6

最近,我发现,这种语法在JavaScript(铬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)此语法如何命名(在[参数1]的部分,让您使用参数1可变)?

2)为什么“情况2”有效?有没有自动转换?

+0

'item1'是如何定义的? – Redu

+0

@Redu它在示例中定义如下:function foo([param1]){} –

+2

[Destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment )。 – Xufox

回答

3

正如@Xufox指出的那样,这是因为destructuringarray destructuring,更具体)。你的第二个例子工作,因为string is an array-like object,所以你得到T,这是param1[0]。数字不是数组(甚至不是数组),所以引擎无法解构参数。

如果你强迫你的电话号码为字符串,它会工作:

​​
2

这似乎是解构为@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 

在上面的例子中,由于字符串是什么,但字符数组,它的实际效果非常好。

0

正如上述那些出色的人所说的那样。以下是计算机如何读取它:

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

但是...

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

不幸的是你的具体用例不一样。抱歉!