Javascript/jQuery中的Python部分等效 [英] Python partial equivalent in Javascript / jQuery
本文介绍了Javascript/jQuery中的Python部分等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python中 functools.partial 的等效项是什么? Javascript还是jQuery?
What is the equivalent for Pythons functools.partial in Javascript or jQuery ?
推荐答案
也许是这样的.这有点棘手,因为javascript没有像python这样的命名参数,但是该函数非常接近.
Something like this perhaps. It is a little bit tricky as javascript doesn't have named arguments like python, but this function comes pretty close.
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>');
这篇关于Javascript/jQuery中的Python部分等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文