【问题标题】:How to apply colors to console.log when using multiple arguments?使用多个参数时如何将颜色应用于 console.log?
【发布时间】:2019-09-02 18:11:55
【问题描述】:

我正在尝试设置 console.log() 的输出样式,以突出显示我的应用程序错误。

到目前为止,这是可行的:

console.log('%cHello World', 'background: #222; color: #bada55');

但这不是:

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

它只返回background: #222; color: #bada55。我错过了什么?

【问题讨论】:

  • 试试这个console.log('%c '+ text, style);

标签: javascript console.log


【解决方案1】:

您使用模板文字在%c 之后的第一个参数中添加text

var text = "Hello World";
var style = "background: #222; color: #bada55";
console.log(`%c${text}`, style);

如果没有模板字符串,它将是

var text = "Hello World";
var style = "background: #222; color: #bada55";
console.log('%c' + text, style);

【讨论】:

    【解决方案2】:

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

    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]);
    

    结果如下:

    【讨论】:

      猜你喜欢
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 2018-12-31
      相关资源
      最近更新 更多