Destructure对象参数,还要引用参数作为对象吗? [英] Destructure object parameter, but also have reference to the parameter as an object?

查看:100
本文介绍了Destructure对象参数,还要引用参数作为对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ES6,你可以在函数参数中构造对象:

With ES6 you can destructure objects in function arguments:

({name, value}) => { console.log(name, value) }

等效的ES5将是:

function(params) { console.log(params.name, params.value) }

但如果我想引用 params 对象和嵌套属性<$ c $,该怎么办? c>值和名称?这是我得到的最接近的,但缺点是它不能用于箭头函数,因为它们无法访问参数对象:

But what if I would like a reference both to the params object and the nested properties value and name? This is the closest I got, but the drawback is that it won't work with arrow functions because they do not have access to the arguments object:

function({name, value}) {
  const params = arguments[0]
  console.log(params, name, value)
}


推荐答案

arguments 在箭头函数中不可用,这会影响在ES6中如何一致地处理函数参数。

arguments isn't available in arrow functions, and this affects how function parameters should be consistently treated in ES6.

如果原始参数是使用时,它应该在函数内部进行解构:

If original parameter is used, it should be destructured inside function:

(param) => {
  const {name, value} = param;
  // ...
}

如果有多个参数可以参考参数协商发生(例如,类似于 arguments.length ),应该使用rest参数:

If several arguments are expected and some argument negotiation takes place (for example, similarly to arguments.length), rest parameter should be used:

(...args) => {
  const [param] = args;
  // ...
}

Boilerplate变量解构有其好处;这种方式更容易在断点处调试 param args ,即使它们当前没有被使用。

Boilerplate variable destructuring has its benefits; it's easier this way to debug param or args at breakpoint even if they aren't currently in use.

这篇关于Destructure对象参数,还要引用参数作为对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆