Multiple assignment in javascript? What does [a,b,c] = [1, 2, 3]; mean?

后端 未结 4 1085
遇见更好的自我
遇见更好的自我 2020-11-22 13:32

For a project a developer sent us a .js file with code similar to this:

var myList = [1,2,3];
var a,b,c;

[a,b,c] = myList;

It works in Ope

4条回答
  •  醉话见心
    2020-11-22 13:48

    Here’s an update on the subject: as of JavaScript version 1.7, destructuring assignments are supported by all major browsers: see browser compatibility.

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

    – MDN’s documentation

    So you can do:

    let a, b;
    [a, b] = ["Hello", "World"];
    
    console.log(a); // "Hello"
    console.log(b); // "World"
    

    Or simply in one line if you're defining the variables:

    let [a, b] = ["Hello", "World"];
    
    console.log(a); // "Hello"
    console.log(b); // "World"
    

提交回复
热议问题