【发布时间】:2018-02-14 00:10:25
【问题描述】:
我有一个函数,如果有错误,它会返回一个字符串,或者如果没有错误,它会返回两个对象。我的函数如下所示:
function logResults(json) {
const one = json[0]
const two = json[1]
const error = json[0].error
if (error) {
return 'error at logResults' // string type
}
return (one, two) // object type
}
我的问题是可以解构这个函数的返回类型吗?如果成功返回两个对象,则此行有效:let [ one, two ] = logResults(json),但如果返回字符串则无效。如果无法进行解构,那么处理不同返回类型的最有效方法是什么?
【问题讨论】:
-
您不能返回“两个对象”。有一个返回值。
return (one, two)到底应该做什么? -
json[0] 和 json[1] 是对象 json 中的嵌套对象。 return (one, two) 将返回 json[0] 和 json[1]。
标签: ecmascript-6 destructuring