2016-10-03 37 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]);

不幸的是你的具體用例不一樣。抱歉!