如何将此代码从 python 复制到 javascript:
myList = [1,2]
a,b = myList[0], myList[1]
print(a) # output 1
print(b) # output 2
请您参考如下方法:
一种解决方案是使用 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;}
