Capturing nested levels in JavaScript destructuring [duplicate]

不羁的心 提交于 2019-12-10 07:39:12

问题


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

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: I'm thinking of something like :as in Clojure or ClojureScript).


回答1:


Yes you can

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})()

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})



回答2:


This is a way

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

f({b:42})

The problem comes up when you need to pass more than one parameter.

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

f({b:42},123)


来源:https://stackoverflow.com/questions/54931090/capturing-nested-levels-in-javascript-destructuring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!