[英]Is possible to pass to a function the properties of an object without the arguments defined and use them by the object's keys?
[英]Apply an object's properties to the arguments of a function
假设我有一个函数(可能来自第 3 方库,假设我无法更改它的定义),以及一个具有与函数参数匹配或重叠的属性的对象:
function fn(foo, bar, baz) { /* do stuff */ }
var obj = { foo: "yes", bar: 7, baz: false }
有没有办法使用某种解构或扩展赋值或其他一些 ES6 功能将对象属性作为函数参数应用,或者我是否坚持单独指定每个参数?
fn(...obj); // Doesn't work
fn(obj.foo, obj.bar, obj.baz); // Convoluted but works
fn.apply(null, obj.values()); // Might work if you're lucky
您可以为fn
创建一个包装函数:
const myFn = ({foo, bar, baz}) => fn(foo, bar, baz);
然后你的电话简化为:
myFn(obj);
这是一个丑陋的黑客,应该避免,但它确实有效(即使对象的值与参数的顺序不同)。
const STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg; const ARGUMENT_NAMES = /([^\\s,]+)/g; function getParamNames(func) { const fnStr = func.toString().replace(STRIP_COMMENTS, ''); let result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); if(result === null) result = []; return result; } function fn(foo, bar, baz) { return {foo, bar, baz}; } const obj = { foo: "yes", baz: false, bar: 7 }; const result = fn(...getParamNames(fn).map(name => obj[name])); console.log(result);
注意: getParamNames
函数的功劳转到如何动态获取函数参数名称/值?
您应该解构函数内部的键-对象对。
const fn = (opts) => { const { foo, bar, baz } = opts; // Your function's "parameters" console.log({ foo, bar, baz }); } const obj = { PI: Math.PI, bar: 7, baz: false, foo: "yes" }; fn(obj);
天真的方法是使用扩展运算符(或 apply-null 技术)调用函数,但这并不能保证对象内的键值对与参数的预期顺序对齐。
function fn(foo, bar, baz) { console.log(arguments); } const obj = { foo: "yes", bar: 7, baz: false }; fn(...Object.values(obj)); // or fn.apply(null, Object.values(obj))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.