简体   繁体   中英

How to store two values from an array in one pass

How to replicate this code from python into javascript:

myList = [1,2]
a,b = myList[0], myList[1]

print(a) # output 1 
print(b) # output 2

One solution is to use destructuring assignment :

 let myList = [1, 2]; let [a, b] = myList; console.log("a is: " + a); console.log("b is: " + b); 
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;} 

If you need to take some particular elements at specific indexes of the array you can do like this:

 let myList = [3, 5, 1, 4, 2]; let [a, b] = [myList[2], myList[4]]; console.log("a is: " + a); console.log("b is: " + b); // Or ... let myList2 = [3, 5, 1, 4, 2]; let {2: c, 4: d} = myList; console.log("c is: " + c); console.log("d is: " + d); 
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;} 

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

This is known as array de-structuring

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring

You need a destructuring assignment , by either

The last one is important, if you like to destructure an array with lots of elements and need just some at some index.

 var myList = [1, 2], [a, b] = myList, { 0: c, 1: d } = myList; console.log(a, b); console.log(c, d); 

You can use ES6 Destructuring assignment.

myList = [1,2];
[value1, value2] = myList;

Now value1 and value2 will have 1 and 2 respectively.

Similarly,

myList = [1,2,3,4,5,6,7,8];
[a,b,...c] = myList;

a and b will have 1 and 2 as their value and c will be an array containing [3,4,5,6,7,8].

Use the snippet below.

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

let myList = [1,2];
let a = myList[0];
let b = myList[1];
console.log(a);
console.log(b);

Using new es6 syntax you can do this.

var myList = [1,2]

var [a,b] = myList
console.log(a)
console.log(b)

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