簡體   English   中英

如何用條件進行對象解構?

[英]How can I do object destructuring with condition?

所以我有:

// some function that returns two arrays ..
getArrays() {
  return {
    arr1: [...],
    arr2: [...]
  };
}

// and then ..
let arr1 = [];
let arr2 = [];
if (someCondition) {
  { arr1, arr2 } = getArrays();
}

// here we expect arrays, even if they are empty ..

當然,這會引發錯誤。 這甚至可能嗎?

PS:我可以使用默認值並直接調用該函數,但仍然 - 我認為它應該是可能的。

一種解決方案是用括號包裝解構表達式:

 // some function that returns two arrays .. function getArrays() { return { arr1: [1], arr2: [2] }; } const someCondition = true; let arr1 = []; let arr2 = []; if (someCondition) { ({ arr1, arr2 } = getArrays()); } console.log(arr1, arr2); 

另一個解決方案是將條件移動到getArrays()函數,如果條件為false返回兩個空數組:

 const getArrays = (condition) => condition ? { arr1: [1], arr2: [2] } : { arr1: [], arr2: [] }; const someCondition = true; const { arr1, arr2 } = getArrays(someCondition); console.log(arr1, arr2); 

您還可以使用函數外部的條件和三元組:

 const getArrays = () => ({ arr1: [1], arr2: [2] }); const someCondition = true; const { arr1, arr2 } = someCondition ? getArrays() : { arr1: [], arr2: [] }; console.log(arr1, arr2); 

暫無
暫無

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

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