Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: modifying a function which prints out variable number of arguments to be recursive?

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/

like image 777
leonOsmania Avatar asked Jun 20 '26 17:06

leonOsmania


1 Answers

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');
like image 76
Nina Scholz Avatar answered Jun 22 '26 06:06

Nina Scholz