Reputation: 101
I have this:
function myalert(x)
{
alert("hey + " x)
}
i am calling a afunction with different parameters
myalert("A");
myalert("B");
myalert("C");
myalert("A");
myalert("B");
myalert("C");
myalert("A");
myalert("B");
myalert("C");
can I avoid that ugly repetition?
update=But what if 2 parameters? How will I make the "LIST" you are talking about? Example:
function myalert(x,y)
{
alert(y + "hey + " x )
}
myalert("A", "X");
myalert("B", "X");
How can i make a list of this?
Upvotes: 1
Views: 58
Reputation: 14094
myalert(['A', 'B', 'C']);
function myalert(dataArray)
{
dataArray.forEach(function(e) {
alert("hey " + x);
});
}
Upvotes: 0
Reputation: 5235
Loop it. You can get function arguments using arguments
and their count arguments.length
.
function myalert()
{
var count = arguments.length;
for(var i = 0; count > i; i++) {
alert("hey + " + arguments[i]);
}
}
myalert('a', 'b', 'c'); // alerts a, alerts b, alerts c
Upvotes: 1
Reputation: 160863
Put all parameters in an array, then use a loop.
var params = ['A', 'B', 'C'];
for (var i = 0, l = parmas.length; i < l; i++) {
myalert(params[i]);
}
or:
['A', 'B', 'C'].forEach(function(e) {
myalert(e);
});
Upvotes: 0