简体   繁体   English

从 function 中解构 object

[英]destructure an object from a function

I need some help with return and destructure an object from a function.我需要一些帮助来从 function 返回和解构 object。 I want to assign new paras to what ever return from the function.我想为从 function 返回的内容分配新的 paras。

function someRes() {
const val1 = 1
const val2 = 2
    return {val1, val2}
}

const {val1, val2} = someRes()
const {val3, val4} = someRes()//this returns as undefined

console.log(val1, val2)
console.log(val3, val4) //console.log undefined

I understand that destructure a params is not like assign them to new params but still, Im looking for an elegant way to do it.我知道解构参数不像将它们分配给新参数,但我仍然在寻找一种优雅的方式来做到这一点。

thank!感谢!

You can use aliases during destructuring.您可以在解构期间使用别名。 When you use destructuring syntax, the variables created assumes the same name as the corresponding object properties.当您使用解构语法时,创建的变量假定与相应的 object 属性名称相同。 You can change that using the : while destructuring:您可以在解构时使用:更改它:

 function someRes() { const val1 = 1 const val2 = 2 return { val1, val2 } } const { val1, val2 } = someRes() const { val1: val3, val2: val4 } = someRes() console.log(val1, val2) console.log(val3, val4)

someRes returns an object with two properties val1 and val2 . someRes返回具有两个属性val1val2的 object 。 Object destructuring requires that you access properties by name so {val3, val4} returns undefined because the object doesn't have those properties. Object 解构要求您按名称访问属性,因此{val3, val4}返回undefined因为 object 没有这些属性。

It looks like you might want to return a tuple instead of an object from your function.看起来您可能想要从 function 返回一个元组而不是 object。 Array destructuring is by index so naming is not constrained by property name. 数组解构是按索引进行的,因此命名不受属性名称的限制。

 function someRes() { const val1 = 1; const val2 = 2; return [val1, val2]; } const [val1, val2] = someRes(); const [val3, val4] = someRes(); console.log(val1, val2); console.log(val3, val4);

Otherwise you can alias the second destructuring assignment as mentioned in the other answer否则,您可以将第二个解构赋值作为另一个答案中提到的别名

 function someRes() { const val1 = 1; const val2 = 2; return {val1, val2}; } const {val1, val2} = someRes(); const {val1: val3, val2: val4} = someRes(); console.log(val1, val2); console.log(val3, val4);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM