在JavaScript解构中捕获嵌套级别 [英] Capturing nested levels in JavaScript destructuring

查看:42
本文介绍了在JavaScript解构中捕获嵌套级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript解构是否具有捕获对象及其内容的语法?

Does JavaScript destructuring have syntax to capture both an object and its content?

换句话说,我是否可以在函数的arg列表中完全执行以下操作而无需以下 const 行?

In other words, can I do the following completely in the function's arg list without the following const line?

f = (a) => {
  const {b} = a;
  console.log("I see:", a, "and", b);
}

f({b:42})

==> I see {b: 42} and 42

(FWIW:我在想Clojure或ClojureScript中的:as 之类的东西.)

(FWIW: I'm thinking of something like :as in Clojure or ClojureScript).

推荐答案

是的

const f = (a, {b} = a ) => {
  console.log("I see:", a, "and", b);
}

f({b:42})

有关解构分配的更多用例,您可以看到此信息

For more use cases of destructuring assignment you can see this

要注意的是:-在函数定义中,请务必保留比函数调用要多的参数.

On side note:- Always keep one extra parameter than you in function definition than than your function call.

更新通过这种方式,您不必担心函数定义中的一个额外参数

Update With this way you need not to worry about one extra parameter in function definition

const f = (...z) => (a=z[0],{b}=z[0],...arguments) => {
  console.log("I see:", a, "and", b, z);
}

f({b:42},{b:32})()

您也可以使用IIFE的@bergi进行尝试,谢谢您的投入.

You can try it with IIFE's too @bergi thanks for inputs.

const f = (a, ...z) => (({b}) => {
  console.log("I see:", a, "and", b, z);
})(a);

f({b:42},{b:32})

这篇关于在JavaScript解构中捕获嵌套级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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