使用多个参数时如何将颜色应用于 console.log?

Che*_*ony 4 javascript console.log

我正在尝试设计我的输出的样式,console.log()以使我的应用程序错误脱颖而出。

到目前为止,这有效:

console.log('%cHello World', 'background: #222; color: #bada55');
Run Code Online (Sandbox Code Playgroud)

但这并没有:

var text = "Hello World";
var style = "background: #222; color: #bada55";
console.log('%c', text, style);
Run Code Online (Sandbox Code Playgroud)

它只是返回background: #222; color: #bada55。我缺少什么?

Арт*_*ьев 8

当您需要记录多个参数时,可以使用以下方法:

const log = (...args) => {
  let messageConfig = '%c%s   ';

  args.forEach((argument) => {
    const type = typeof argument;
    switch (type) {
        case 'bigint':
        case 'number':
        case 'boolean':
            messageConfig += '%d   ';
            break;

        case 'string':
            messageConfig += '%s   ';
            break;

        case 'object':
        case 'undefined':
        default:
            messageConfig += '%o   ';
    }
  });

  console.log(messageConfig, 'color: orange', '[LOGGER]', ...args);
};

log('my message', 123, 'qwerty', { foo: 'bar' }, [1, 2, 3, 4, 5]);
Run Code Online (Sandbox Code Playgroud)

这是结果: 在此输入图像描述