如何将此代码从python复制到javascript:
myList = [1,2]
a,b = myList[0], myList[1]
print(a) # output 1
print(b) # output 2
最后一个很重要,如果你想要构造一个包含大量元素的数组,并且只需要一些索引。
var myList = [1, 2],
[a, b] = myList,
{ 0: c, 1: d } = myList;
console.log(a, b);
console.log(c, d);
一种解决方案是使用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;}
如果需要在数组的特定索引处获取某些特定元素,可以这样做:
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)
这称为阵列解构
您可以使用ES6 Destructuring assign。
myList = [1,2];
[value1, value2] = myList;
现在value1和value2分别有1和2。
同样的,
myList = [1,2,3,4,5,6,7,8];
[a,b,...c] = myList;
a和b的值为1和2,c为包含[3,4,5,6,7,8]的数组。
使用下面的代码段。
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);
使用新的es6语法可以做到这一点。
var myList = [1,2]
var [a,b] = myList
console.log(a)
console.log(b)