Question

I have a customized (console.)log function

function clog(toConsole, toFile){
    console.log(toConsole);
    // other things
}

But now I can't pass it the string in 'value: %d', value format

...unless I wrap it in an array

clog(['to console: %d', value], 'other things'])

Is there a way to pass the elements of the array ['to console: %d', value] to a function like: console.log('to console: %d', value)

Était-ce utile?

La solution

What you are looking for is Function.prototype.apply. It allows you to call a function with an array, which is filled in as the arguments. In this case

console.log.apply(console, ['to console: %d', value]);

will be equivalent to

console.log('to console: %d', value);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top