Passing the elements of an array as argument list to a function (not as a combined string)

StackOverflow https://stackoverflow.com/questions/23211124

سؤال

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)

هل كانت مفيدة؟

المحلول

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);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top