Gần đây tôi phát hiện ra rằng cú pháp này hoạt động trong JavaScript (Chrome 53):tên phần tử mảng được sử dụng trong định nghĩa hàm
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
tôi thấy param1 có thể được sử dụng như là biến tham chiếu đến mục với chỉ số 0 trong số đầu tiên (được khai báo là mảng).
Câu hỏi của tôi là:
1) Cú pháp này được đặt tên như thế nào (phần [param1] cho phép bạn sử dụng param1 làm biến)?
2) Tại sao "Case 2" hoạt động? Có bất kỳ chuyển đổi tự động nào không?
cách 'item1' được xác định? – Redu
@Redu nó được định nghĩa như trong ví dụ: function foo ([param1]) {} –
[Destructuring] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). – Xufox