Javascript Array 有一个填充函数:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
所以你可以写这样的东西
$(
new Array(copies).fill(function () {
return $(this).clone();
}.bind(el))
.map(function (el) {
return el();
})
).map(function() { return this.toArray(); }); //Turn into jQuery
如果你想把它作为一个可以重用的 jQuery 函数,你可以写这样的东西
$.fn.multiply = function(amount) {
var cloneFunction = (function() {
return $(this).clone();
}).bind(this);
return $(
new Array(amount).fill(cloneFunction).map(function(el) {
return el();
});
).map(function() { return this.toArray(); }); //Turn into jQuery
}
这使您可以灵活地将克隆的函数调用与仅在需要时进行评估分开。因此,如果您愿意,可以拆分通话并稍后进行评估。
意味着这是承诺(它返回具有绑定上下文的函数 this 调用时将克隆)
new Array(amount).fill(cloneFunction);
这就是决议
.map(function(el) { return el(); })
最后一点处理了我创建了一个 jQuery 对象数组但我真的想要一个 jQuery 集合的事实
.map(function() { return this.toArray(); }); //Turn into jQuery
但无论如何,如果你走这条路,你的最终解决方案看起来像这样。
$(el).multiply(amount).insertAfter(anotherEl);
干杯