簡體   English   中英

用作 function 參數時的 JavaScript 數組解構問題

[英]JavaScript array destructuring issue when used as function parameters

當我解構一個空數組並將其作為參數傳遞給我的 function 時,它會出現在我沒想到的地方。

這就是你應該如何將數組解構為 function 參數:

 let test = (one, two, three) => { console.log(one); console.log(two); console.log(three); }; test(...[1, 2, 3]); // returns 1, 2, 3

但是在我的情況下,我想將數組解構為單個 function 參數。

有時這個數組是空的,但否則它只有一個 object。 它沒有按預期工作:

 let test = (one, two, three) => { if (three === undefined) { console.log("3 is undefined"); } }; test(...[], 2, 3); // 3 is undefined

three是未定義的,但這肯定不是真的,因為one未定義的。

到底是怎么回事?

當您將可迭代對象傳播到參數列表中時,可迭代對象的所有元素都將插入到該點的參數列表中,並且 arguments 的 rest 將在該點的末尾開始。 但是一個空數組不包含任何元素。 把這個:

...[],

在參數列表中什么都不做 - 它相當於一個段根本不存在,因為它沒有插入 arguments,並且 arguments 位於...[],的右側,它們從其他位置開始。

test(...[], 2, 3);

是相同的

test(2, 3);

所以

let test = (one, two, three) => {

onetwo得到分配給它們的數字, three是未定義的 - 因為總共通過了兩個 arguments。

另請注意,您的問題中根本沒有解構 - 您所做的只是調用傳播語法

let test = (one, two, three) => {
  if (one === undefined) {
    console.log("3 is undefined");
  }else{
  console.log(one)
  }
};

test(...[], 2, 3);

第一個參數是2,第二個是3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM