解构 JavaScript 中的元组

Destructuring tuples in JavaScript

我正在尝试解构一个元组:

tuple = [[1,"word",3,4,5],[1,"hello",3,4,5],[1,"word",3,4,5]]

像这样:

let destruct = [item1, item2, item3, item4, item5] = [tuple]

但是元组中的所有内容都分配给 item1。是否可以将元组中的每个数组实际映射到第二个数组中的 5 个项目?

预期输出:

item2[0] = "word",
item2[1] = "hello

编辑:有人回答 tuples.map 得到了预期的结果,但答案已被删除?此外,是否可以采用纯破坏性解决方案?

元组周围有额外的括号,试试这个

const tuple = [[1,"word",3,4,5],[2,"word",3,4,5],[3,"word",3,4,5]]
const [item1, item2, item3, item4, item5] = tuple

console.log(item3)

您可以在 javascript

中解构数组或对象
let tuple = [[1,"word",3,4,5],[1,"word",3,4,5],[1,"word",3,4,5]]

let [item1, item2, item3] = tuple

你甚至可以得到嵌套值如下

let [item1, [one, word, three], item3] = tuple;
console.log(one)  // 1
console.log(word)  // 'word'
console.log(three)  // 3

使用嵌套 map(),从第一个开始获取索引,然后用它来创建每个 'column':

const [ ] = tuple[0].map((_, i) => tuple.map((_, j) => tuple[j][i]))

const tuple = [[1,"word",3,4,5],[1,"hello",3,4,5],[1,"word",3,4,5]];

const [ item1, item2, item3, item4, item5 ] = tuple[0].map((_, i) => tuple.map((_, j) => tuple[j][i]));

console.log(item2[0], item2[1]); // word hello
console.log(item4);              // [ 4, 4, 4 ]