Javascript 为什么传播和破坏是不同的,即使他们似乎做了类似的工作

Javascript 为什么传播和破坏是不同的,即使他们似乎做了类似的工作,javascript,Javascript,传播和破坏工作各不相同,但它们似乎都做了类似的工作。为什么它们不同,为什么不只用一个呢 let foo = [1,2,3]; let [o,t,th] = foo; //destructing works let [o,t,th] = ...foo; // spreading doesn't work. will not compile function test (a,b,c) { console.log(`${a}, ${b}, ${c}`) } test(...foo); //wo

传播和破坏工作各不相同,但它们似乎都做了类似的工作。为什么它们不同,为什么不只用一个呢

let foo = [1,2,3];
let [o,t,th] = foo; //destructing works

let [o,t,th] = ...foo; // spreading doesn't work. will not compile

function test (a,b,c) {
 console.log(`${a}, ${b}, ${c}`)
}

test(...foo); //works but is sort of destructinng foo into a,b,c
test(foo) //assigns foo to a. b and c are undefined.

解构

let [o,t,th] = [1, 2, 3];
这里您声明了三个变量,同时直接从数组元素为它们赋值

因此,解构是一种直接访问对象(can)的方法 也可以是数组)属性,而无需显式将其分配给 变量

这相当于:

let o = foo[0];
let t = foo[1];
let th = foo[2];
test(foo[0], foo[1], foo[2]);
价差

test(...foo);
这里将数组元素分散到逗号分隔的数组元素

这相当于:

let o = foo[0];
let t = foo[1];
let th = foo[2];
test(foo[0], foo[1], foo[2]);

因此,这两者是不同的。

首先,你应该注意这一点

[a, b, c]

这是两件完全不同的事情。当然它们都有逗号和相同的字母,但是
a,b,c中的
func(a,b,c)
不是数组

test(…foo)
中,
…foo
将数组的内容作为逗号分隔的参数进行传播。这与将数组传递到函数中不同


let[o,t,th]=…foo不起作用,因为规范不允许这样使用。不管怎么说,这没有道理。你想把
foo
的内容传播到什么地方

然而,这是有道理的:

[...foo]  // spread the content into an array
只有当您将一件事分配给一组变量时,Destructure才起作用。例子包括:

let [a, b] = [1, 2];
let {a, b} = {a: 1, b: 2};
function([a, b]){};

什么是
foo
开始?oops
让foo=[1,2,3]
让[o,t,th]=…foo应该是
让[o,t,th]=[…foo]因为它们不相似。解构从数组/对象中取出某些元素,然后将所有数据分散到新的数组/对象/参数中list@talentedandrew没有工作
let[o,t,th]=[…foo]