Javascript用参数多次调用一个函数 [英] Javascript call a function several times with the arguments
本文介绍了Javascript用参数多次调用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这不是完全必要的,我只是在尝试简化我的代码.这就是我所拥有的:
This isn't totally necessary, I'm just trying to simplify my code. This is what I have:
function fillWebsitePlaceFiller(number) {
document.getElementById("placefillerWebsite" + number).innerHTML = placefillerWebsite;
}
fillWebsitePlaceFiller(1);
fillWebsitePlaceFiller(2);
fillWebsitePlaceFiller(3);
fillWebsitePlaceFiller(4);
fillWebsitePlaceFiller(5);
fillWebsitePlaceFiller(6);
fillWebsitePlaceFiller(7);
有没有一种方法可以只调用一次函数,并且每个参数将通过它运行7次?
Is there a way I can call the function just once, and it will run through it 7 times with each argument?
推荐答案
方法1-迭代
for (var i = 1; i < 8; i++) fillWebsitePlaceFilter(i);
方法2-递归
(function repeat(number) {
fillWebsitePlaceFiller(number);
if (number > 1) repeat(number - 1);
})(7);
方法3-函子应用
[1, 2, 3, 4, 5, 6, 7].forEach(fillWebsitePlaceFiller);
方法4-内部迭代
function fillWebsitePlaceFiller(times) {
for (var number = 1; number <= times; number++) {
document.getElementById("placefillerWebsite" + number).innerHTML = placefillerWebsite;
}
}
方法5-扩展功能行为
Function.prototype.sequence = function(from, to) {
for (var i = from; i <= to; i++) this.call(null, i);
};
fillWebsitePlaceFiller.sequence(1, 7);
方法6-XPath(警告:未测试)
Method 6 - XPath (warning: not tested)
var query = '//*[@id[starts-with(., "placefillerWebsite"]]';
var result = document.evaluate(query, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
while (var node = result.iterateNext()) node.innerHTML = placefillerWebsite;
方法7-jQuery
Method 7 - jQuery
$('[id^="placefillerWebsite"]').html(placefillerWebsite)
我推荐一种您不假定总是有七个的方法.
I recommend one of the methods where you don't assume there are always seven of them.
这篇关于Javascript用参数多次调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文