Chrome JavaScript developer console: Is it possible to call console.log() without a newline?

前端 未结 12 889
生来不讨喜
生来不讨喜 2020-11-29 05:07

I\'d like to use console.log() to log messages without appending a new line after each call to console.log(). Is this possible?

12条回答
  •  无人及你
    2020-11-29 05:38

    Yes, it's possible (check out the demo below) -- by implementing your own virtual console on top of the native browser console, then syncing it to the real one.

    This is much easier than it sounds:

    1. maintain a display buffer (e.g. an array of strings representing one line each)
    2. call console.clear() before writing to erase any previous contents
    3. call console.log() (or warn, error, etc) to fill the console with the contents from your display buffer

    Actually, I've been doing this for some time now. A short, rudimentary implementation of the idea would be something along the following lines, but still capable of animating the console contents:

    // =================================================
    // Rudimentary implementation of a virtual console.
    // =================================================
    
    var virtualConsole = {
        lines: [],
        currentLine: 0,
        log: function (msg, appendToCurrentLine) {
            if (!appendToCurrentLine) virtualConsole.currentLine++;
          
            if (appendToCurrentLine && virtualConsole.lines[virtualConsole.currentLine]) {
                virtualConsole.lines[virtualConsole.currentLine] += msg;
            } else {
                virtualConsole.lines[virtualConsole.currentLine] = msg;
            }
            
            console.clear();
            
            virtualConsole.lines.forEach(function (line) {
                console.log(line);
            });
        },
        clear: function () {
            console.clear();
            virtualConsole.currentLine = 0;
        }
    }
    
    // =================================================
    // Little demo to demonstrate how it looks.
    // =================================================
    
    // Write an initial console entry.
    virtualConsole.log("Loading");
    
    // Append to last line a few times.
    var loadIndicatorInterval = setInterval(function () {
        virtualConsole.log(".", true); // <- Append.
    }, 500);
    
    // Write a new line.
    setTimeout(function () {
        clearInterval(loadIndicatorInterval);
        virtualConsole.log("Finished."); // <- New line.
    }, 8000);

    It sure has its drawbacks when mixing with direct console interaction, and can definitely look ugly -- but it certainly has its valid uses, which you couldn't achieve without it.

提交回复
热议问题