0

I know I can put item by item to variable like:

var array = [15,20];
var a = array[0];
var b = array[1];

But I curious how to put array values in multi variable in one line like list() in php:

list($a,$b) = [15,20]; // $a = 15, $b = 20

Is it possible or not ?!

ttrasn
  • 3,457
  • 4
  • 26
  • 38

2 Answers2

4

Use javascript's array de-structuring syntax,

var array = [15,20];
const [x, y] = array;
Gangadhar Gandi
  • 1,884
  • 10
  • 16
  • very good, thanks, Its better to set `var` instead of `const` to can change later – ttrasn Nov 12 '19 at 11:03
  • @ttrasn No, `const` is better because you should always avoid needing to reassign a variable. But if you need to, you should use `let` instead of `var`. – Lennholm Nov 12 '19 at 11:29
  • 1
    Keep in mind this a relatively new JavaScript feature. All relevant, current browsers support it, but for example Internet Explorer (11 and before) does not. See: https://caniuse.com/#feat=mdn-javascript_operators_destructuring – RoToRa Nov 12 '19 at 11:32
0

You can use: Destructuring assignment - Javascript 1.7

matches = ['12', 'watt'];
[value, unit] = matches;
console.log(value,unit)
Rohit.007
  • 3,324
  • 2
  • 18
  • 29