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

后端 未结 4 1028
遇见更好的自我
遇见更好的自我 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"
    
    0 讨论(0)
  • 2020-11-22 13:53

    This is a feature called destructuring assignment, which was added in JavaScript 1.7 and ECMAScript 6. It is not a part of ECMAScript 5: What is cross browser support for JavaScript 1.7's new features? Specifically array comprehensions and the "let" statement

    0 讨论(0)
  • 2020-11-22 14:12

    This is destructuring assignment, available in Javascript 1.7 (mozilla) and some newer browsers: http://www.robertnyman.com/javascript/javascript-1.7.html#destructuring-assignment

    0 讨论(0)
  • 2020-11-22 14:14

    Opera's older "futhark" JavaScript engine had support for this, but it was dropped in the new engine "carakan", because it was non-standard, not required on the web, and would complicate the new and very fast implementation.

    0 讨论(0)
提交回复
热议问题