JavaScript:将数组拆分为单独的变量

Wic*_*ick 4 javascript arrays variables split

考虑这个数据结构:

var vehicles = [
  [ "2011","Honda","Accord" ],
  [ "2010","Honda","Accord" ],
  .....
];
Run Code Online (Sandbox Code Playgroud)

循环遍历每个车辆项,是否有一种方法可以一次性将数组元素重新分配给各个变量,例如:

for (i = 0; i < vehicles.length; i++) {
  var(year,make,model) = vehicles[i]; // doesn't work
  .....
}
Run Code Online (Sandbox Code Playgroud)

...我试图摆脱这样做:

for (i = 0; i < vehicles.length; i++) {
  var year = vehicles[i][0];
  var make = vehicles[i][1];
  var model = vehicles[i][2];
  .....
}
Run Code Online (Sandbox Code Playgroud)

只是好奇,因为这种类型的东西在其他编程语言中也可用。谢谢!

Moh*_*man 6

现在可以使用 ES6 的数组解构。

从文档来看:

解构赋值语法是一种 JavaScript 表达式,可以将数组中的值或对象中的属性解压到不同的变量中。

考虑以下示例:

let [a, b, c] = [10, 20, 30];

console.log(a);  // output => 10
console.log(b);  // output => 20
console.log(c);  // output => 30
Run Code Online (Sandbox Code Playgroud)

与数据一样,.forEach()方法也可用于迭代数组元素以及数组解构:

let vehicles = [
  [ "2011","Honda","Accord" ],
  [ "2010","Honda","Accord" ]
];

vehicles.forEach(([year, make, model], index) => {
  // ... your code here ...
  console.log(`${year}, ${make}, ${model}, ${index}`);
});
Run Code Online (Sandbox Code Playgroud)

参考: