如何进行有条件的对象破坏?

时间:2018-11-02 12:15:11

标签: javascript ecmascript-6 destructuring

所以我有

// 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:我可以使用默认值并直接调用该函数,但是-我认为应该可以。

1 个答案:

答案 0 :(得分:6)

一种解决方案是用括号括起解构表达式:

// 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);

相关问题