将数组的元素作为参数列表传递给函数(而不是作为组合字符串)

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

本文关键字:组合 函数 字符串 元素 数组 参数 列表      更新时间:2023-09-26

我有一个自定义的(控制台)日志函数

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

但现在我无法将'value: %d', value格式的字符串传递给它

除非我把它包装在阵列中

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

有没有一种方法可以将数组['to console: %d', value]的元素传递给函数,如:console.log('to console: %d', value)

您要查找的是Function.prototype.apply。它允许您调用带有数组的函数,数组作为参数填写。在这种情况下,

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

将相当于

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