Zit*_*rax 4 javascript python jquery
在Javascript或jQuery中,Python的functools.partial等效于什么?
这是一个适用于 的简单解决方案ES6。但是,由于 javascript 不支持命名参数,因此在创建部分时您将无法跳过参数。
const partial = (func, ...args) => (...rest) => func(...args, ...rest);
Run Code Online (Sandbox Code Playgroud)
例子
const greet = (greeting, person) => `${greeting}, ${person}!`;
const greet_hello = partial(greet, "Hello");
>>> greet_hello("Universe");
"Hello, Universe!"
Run Code Online (Sandbox Code Playgroud)
大概是这样的。这有点棘手,因为javascript没有像python这样的命名参数,但是该函数非常接近。
function partial() {
var args = Array.prototype.slice.call(arguments);
var fn = args.shift();
return function() {
var nextArgs = Array.prototype.slice.call(arguments);
// replace null values with new arguments
args.forEach(function(val, i) {
if (val === null && nextArgs.length) {
args[i] = nextArgs.shift();
}
});
// if we have more supplied arguments than null values
// then append to argument list
if (nextArgs.length) {
nextArgs.forEach(function(val) {
args.push(val);
});
}
return fn.apply(fn, args);
}
}
// set null where you want to supply your own arguments
var hex2int = partial(parseInt, null, 16);
document.write('<pre>');
document.write('hex2int("ff") = ' + hex2int("ff") + '\n');
document.write('parseInt("ff", 16) = ' + parseInt("ff", 16));
document.write('</pre>');Run Code Online (Sandbox Code Playgroud)