Search code examples
javascriptarraysparameterscallapply

Passing an array as a built-in function parameter in JavaScript


I need to pass an array as built-in function. For example this works fine:

console.info('%cBlue text%c Red text', 'color:blue', 'color:red');

There are 3 parameters, but what should I do when I got n parameter?

var x = [ '%cBlue text%c Red text...%c nth-Text', 'color:blue', 'color:red', ... , 'nth-color:black']; 
console.info.apply(null, x);

does not work. Thanks in advance.


Solution

  • It fails because you pass null as context instead of the console object. This works :

    console.info.apply(console, x);
    

    More generally, you can use apply for your own functions too, but when they need a context, you must set it.