简体   繁体   English

如何一次存储数组中的两个值

[英]How to store two values from an array in one pass

How to replicate this code from python into javascript: 如何将此代码从python复制到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;} 

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. 您可以使用ES6解构分配。

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

Now value1 and value2 will have 1 and 2 respectively. 现在,value1和value2将分别具有1和2。

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]. a和b的值分别为1和2,c为包含[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. 使用新的es6语法,您可以执行此操作。

var myList = [1,2]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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