JavaScript 解构是否具有捕获对象及其内容的语法?
换句话说,我可以在函数的参数列表中完全执行以下操作而不使用以下内容吗const
line?
f = (a) => {
const {b} = a;
console.log("I see:", a, "and", b);
}
f({b:42})
==> I see {b: 42} and 42
(FWIW:我正在考虑类似的事情:as
在 Clojure 或 ClojureScript 中)。
是的你可以
const f = (a, {b} = a ) => {
console.log("I see:", a, "and", b);
}
f({b:42})
更多使用案例解构赋值 https://stackoverflow.com/questions/54605286/what-is-destructuring-assignment-and-its-uses你可以看到这个
旁注:-始终在函数定义中比函数调用多保留一个参数。
Update通过这种方式,您不必担心函数定义中的一个额外参数
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 感谢您的投入。
const f = (a, ...z) => (({b}) => {
console.log("I see:", a, "and", b, z);
})(a);
f({b:42},{b:32})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)