简体   繁体   中英

Combining JavaScript Arrays Dynamically

I'm writing a JavaScript function to combine arrays. I'd like to be able to accept a variable number of arrays as arguments passed into the function, but I can't seem to get it to work. I tried the following:

        var args = Array.prototype.slice.call(arguments, 1);
        var retArray = [];
        args.forEach(function(a) {
            return retArray.concat(a);
        });
        return retArray;

But with no success. Am I missing something?

Try this.

function foo() {
    var combinedArr = Array.prototype.concat.apply([], arguments);
    console.log(combinedArr);
}

foo([1, 2], [4, 3, 5], [6, 7, 8]);

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