I've created a Javascript function which takes a variable number of arguments and prints each out on a new line:
var printOut = function () {
for (var i = 0; i < arguments.length; i++) {
document.writeln(arguments[i] + '<br>');
}
};
printOut('a', 'b', 'c');
printOut('d', 'e');
The function prints out:
a
b
c
d
e
What I'd like to know is whether it's possible to take this function and make it recursive, but the output is in the same order? From what I've studied, recursion would reverse the order of the output no?
Fiddle: https://jsfiddle.net/klems/kao9bh6v/
You could slice the arguments and call the function again with apply.
var printOut = function () {
if (arguments.length) {
console.log(arguments[0]);
printOut.apply(null, [].slice.call(arguments, 1));
}
};
printOut('a', 'b', 'c');
printOut('d', 'e');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With