假设我正在以这种方式使用方法:
const {a, b} = foobar()
// or...
const obj = foobar()
const {a, b} = obj
在
foobar
函数中有没有办法判断它的结果是立即被解构,还是存储在变量/常量中?或者它在那个点/那个范围内没有上下文,除非你在参数中传递它?
// Is this the only way?
const {a, b} = foobar({ isDestructured: true })
在 JavaScript 中没有这样的语法可以帮助你。
但是,我认为您可以通过使用另一个功能轻松实现您想要的:
function thatReturnsComplexOutput() {
return {a: 'some', b: 'thing'};=
}
function thatReturnsOnlyA() {
return thatReturnsComplexOutput().a;
}
在 JavaScript 中,您可以使用
typeof
运算符来确定函数的返回值是被解构还是按原样使用。当一个函数的返回值被解构时,它的类型将是一个对象或一个数组。当它按原样使用时,它的类型将取决于函数的返回值。
例如,假设您有一个名为 getPerson() 的函数,它返回一个具有属性名称和年龄的对象。如果你解构函数的返回值,结果的类型将是一个对象:
const { name, age } = getPerson();
console.log(typeof { name, age }); // "object"
另一方面,如果按原样使用函数的返回值,类型将取决于函数的返回值。例如,如果
getPerson()
返回一个字符串,则结果的类型将是一个字符串:
const name = getPerson();
console.log(typeof name); // "string"
因此,简而言之,您可以使用
typeof
通过检查分配给函数返回值的值的类型来确定函数的返回值是否被解构或按原样使用。