JS数组解构赋值疑问:该写法与常规变量声明是否等价?它叫什么?
Hey there! Great question—let’s break this down step by step:
1. 两种写法是否等价?
Absolutely! The line const [input,button] = form.elements; does exactly the same thing as:
const input = form.elements[0]; const button = form.elements[1];
Both snippets create two const variables, input and button, assigned to the first and second elements of form.elements respectively. No functional difference here—just a shorter, cleaner syntax.
2. 这是什么语法?
This is called Array Destructuring Assignment, a feature introduced in ES6 (ECMAScript 2015) as part of the broader destructuring assignment syntax.
Destructuring lets you extract values from arrays (or properties from objects) and assign them to variables in a single line, making code more concise and readable. For example:
// Basic array destructuring example const [first, second, third] = [10, 20, 30]; // Equivalent to: // const first = 10; // const second = 20; // const third = 30;
A quick note: form.elements returns an HTMLFormControlsCollection, which is an array-like object. ES6 destructuring works with array-like objects as long as they implement the iterable interface (which this collection does), so it’s safe to use here.
内容的提问来源于stack exchange,提问作者Housemartin

