简体   繁体   中英

JavaScript Pattern: Is this a valid way of assigning multiple values to an array?

I have seen that pattern on CodeReview: https://codereview.stackexchange.com/questions/144954/generate-a-table-with-random-numbers

The last function "shuffeledArray".

The following code is used to assign multiple values to an array in one operation:

 var demo = []; [demo[0], demo[1], demo[2]] = [2, 4, 8]; console.log(demo); 

It works.

But I ask myself:

Shall one use these technique? Or are there disadvantages?

It's just a poor example of a useful feature: Destructuring assignment.

A better example makes the usefulness of destructuring assignment a bit more apparent. Consider the case where a function needs to return more than one return value. Normally, we return an object or an array. With destructuring assignment, we can consume that return value with individual variables:

As an object:

 function minMax(a) { let min = a[0], max = a[0]; a.forEach(entry => { if (min > entry) { min = entry; } if (max < entry) { max = entry; } }); return {min, max}; } let {min, max} = minMax([2, 4, 8]); console.log(min, max); 

As an array:

 function minMax(a) { let min = a[0], max = a[0]; a.forEach(entry => { if (min > entry) { min = entry; } if (max < entry) { max = entry; } }); return [min, max]; } let [min, max] = minMax([2, 4, 8]); console.log(min, max); 

Destructuring with objects is particularly useful, for instance, when dealing with modules. Suppose a module exports a whole slew of things, of which you need only foo and bar :

import {foo, bar} from "./module";

With regard to the browser support argument for not using it: That's what transpiling is for. I've been happily using ES2015 in projects meant for browsers all the way back to IE9 for over two years (yes, before the spec was finalized), thanks to transpiling.

The syntax is ES6 and is perfectly valid, to make it compatible with exsiting browsers, you may need to use babel or tracer to compile your ES6 code to ES5 code to run in browser.

var [a, b] = [1, 2];
console.log(a, b);

The above code is valid of assigning 1 and 2 to a and b respectively.

var [a, ...b] = [1, 2, 3];
console.log(a, b);

In the above code we are using spread operator assigning a = 1 and b = [2,3]

Loon on more topics on Array destructing.

http://www.2ality.com/2015/01/es6-destructuring.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM