如何使用条件进行对象解构?
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
return两个空数组:
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);
所以我有:
// 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
return两个空数组:
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);