Dav*_*arb 4 javascript destructuring
JavaScript解构是否具有捕获对象及其内容的语法?
换句话说,如果没有以下const行,我可以在函数的arg列表中完全执行以下操作吗?
f = (a) => {
const {b} = a;
console.log("I see:", a, "and", b);
}
f({b:42})
==> I see {b: 42} and 42
Run Code Online (Sandbox Code Playgroud)
(FWIW:我在想:asClojure或ClojureScript中的东西).
是的你可以
const f = (a, {b} = a ) => {
console.log("I see:", a, "and", b);
}
f({b:42})Run Code Online (Sandbox Code Playgroud)
有关解构分配的更多用例,您可以看到这一点
注意事项: -在功能定义中保留一个额外的参数,而不是函数调用.
更新使用这种方式,您无需担心函数定义中的一个额外参数
const f = (...z) => (a=z[0],{b}=z[0],...arguments) => {
console.log("I see:", a, "and", b, z);
}
f({b:42},{b:32})()Run Code Online (Sandbox Code Playgroud)
您也可以尝试使用IIFE @bergi感谢输入.
const f = (a, ...z) => (({b}) => {
console.log("I see:", a, "and", b, z);
})(a);
f({b:42},{b:32})Run Code Online (Sandbox Code Playgroud)