繁体   English   中英

功能参数解构

[英]Destructuring in function parameters

假设我们具有这样的功能:

const func = (a, b, {c: {d}}) => {console.dir(c)}

该函数应如何调用以及第三个参数的结构? 我尝试了很多变体,但始终遇到错误: Cannot destructure property of 'undefined' or 'null'. Cannot destructure property d of 'undefined' or 'null'.

谢谢!

 const func = (a, b, {c: {d}}) => {console.dir(d)} func(null, null, {c: {d: document.location}}); 

必须使用具有键c对象调用此函数,该对象具有键d为值的对象:

func(a, b, {c: {d: document.location }}) 

console.dir()将任何JS对象作为参数。

{ c: {d}}是一种称为对象解构的语法,其目的是从作为函数参数传递的对象中解压缩字段。

{d}是具有键d和值d{d: d} )的对象的较短语法。

要从键c下的对象中解压缩变量d ,该对象必须初始化该键! 但是,当您进一步对作为参数传递的对象进行解构时,在范围内就没有该对象作为变量。

在您提供的示例中,您将无法访问对象c ,因为它已被解构并且只有对象d可用。 您可能在代码中有误,或者需要发布类似Anurat Chapanond的内容。

这是一个例子。

const func = (a, b, {c: {d}}) => {console.dir(c)},
    c = { d: 'hello' }

func(1, 2, { c })

我将c定义为具有属性d(字符串“ hello”)的对象。

当调用func时,我传递给函数的第三个参数是具有属性c的对象。

{c}是{c:c}的简写

暂无
暂无

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

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