问题
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