简体   繁体   中英

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM