在JavaScript中将数组作为内置函数参数传递

时间:2023-01-15 20:51:09

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?

有3个参数,但是当我得到n参数时该怎么办?

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.

不起作用。提前致谢。

1 个解决方案

#1


2  

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

它失败是因为您将null作为上下文而不是控制台对象传递。这有效:

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.

更一般地说,您也可以使用apply来处理自己的函数,但是当它们需要上下文时,您必须设置它。

#1


2  

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

它失败是因为您将null作为上下文而不是控制台对象传递。这有效:

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.

更一般地说,您也可以使用apply来处理自己的函数,但是当它们需要上下文时,您必须设置它。