最近,我發現,這種語法在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」有效?有沒有自動轉換?
'item1'是如何定義的? – Redu
@Redu它在示例中定義如下:function foo([param1]){} –
[Destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment )。 – Xufox