Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  53] [ 6]  / answers: 1 / hits: 69403  / 11 Years ago, fri, july 12, 2013, 12:00:00

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);


Is there a way I can call the function just once, and it will run through it 7 times with each argument?


More From » javascript

 Answers
32

Method 1 - iteration


for (var i = 1; i < 8; i++) fillWebsitePlaceFilter(i);

Method 2 - recursion


(function repeat(number) {
fillWebsitePlaceFiller(number);
if (number > 1) repeat(number - 1);
})(7);

Method 3 - functor application


[1, 2, 3, 4, 5, 6, 7].forEach(fillWebsitePlaceFiller);

Method 4 - internal iteration


function fillWebsitePlaceFiller(times) {
for (var number = 1; number <= times; number++) {
document.getElementById("placefillerWebsite" + number).innerHTML = placefillerWebsite;
}
}

Method 5 - extend function behaviour


Function.prototype.sequence = function(from, to) {
for (var i = from; i <= to; i++) this.call(null, i);
};

fillWebsitePlaceFiller.sequence(1, 7);

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;

Method 7 - jQuery


$('[id^="placefillerWebsite"]').html(placefillerWebsite)

I recommend one of the methods where you don't assume there are always seven of them.


[#77029] Thursday, July 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ibrahimr

Total Points: 468
Total Questions: 99
Total Answers: 93

Location: Serbia
Member since Sun, Jul 11, 2021
3 Years ago
;