Javascript数组有一个fill函数:
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(); });
如果你想把它作为一个可重复使用的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(); });
}
这使您能够灵活地将克隆函数的调用与仅在需要时进行评估分开。因此,如果您想要,可以拆分调用并稍后进行评估。
这意味着这是一个承诺(它返回绑定到此上下文的函数,当调用时将进行克隆)
new Array(amount).fill(cloneFunction);
这就是解决方案
.map(function(el) { return el(); })
这个小的最后一部分处理了一个问题,即我创建了一个jQuery对象数组,但实际上我想要一个jQuery集合
.map(function() { return this.toArray(); });
但无论如何,如果你选择这种方法,你最终的解决方案会是这个样子。
$(el).multiply(amount).insertAfter(anotherEl);
干杯