简体   繁体   English

Chrome JavaScript 开发者控制台:是否可以在没有换行符的情况下调用 console.log()?

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

I'd like to use console.log() to log messages without appending a new line after each call to console.log().我想使用 console.log() 来记录消息,而无需在每次调用 console.log() 后追加新行。 Is this possible?这可能吗?

No, it's not possible.不,这不可能。 You'll have to keep a string and concatenate if you want it all in one line, or put your output elsewhere (say, another window).如果您希望将其全部放在一行中,则必须保留一个字符串并进行连接,或者将您的输出放在其他地方(例如,另一个窗口)。

In NodeJS you can use process.stdout.write and you can add '\\n' if you want.在 NodeJS 中,您可以使用 process.stdout.write 并且可以根据需要添加 '\\n'。

console.log(msg) is equivalent to process.stdout.write(msg + '\\n') . console.log(msg)等价于process.stdout.write(msg + '\\n')

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 (eg an array of strings representing one line each)维护一个显示缓冲区(例如一个字符串数组,每个字符串代表一行)
  2. call console.clear() before writing to erase any previous contents在写入之前调用console.clear()以擦除任何以前的内容
  3. call console.log() (or warn, error, etc) to fill the console with the contents from your display buffer调用console.log() (或警告、错误等)用显示缓冲区中的内容填充控制台

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.当与直接的控制台交互混合时,它肯定有其缺点,并且肯定看起来很丑 - 但它肯定有其有效用途,没有它你就无法实现。

You can put as many things in arguments as you'd like:您可以根据需要在arguments放入任意数量的内容:

console.log('hi','these','words','will','be','separated','by','spaces',window,document)

You'll get all that output on one line with the object references inline and you can then drop down their inspectors from there.您将在一行中获得所有输出,并带有内联的对象引用,然后您可以从那里下拉他们的检查员。

The short answer is no.最简洁的答案是不。

But

If your use-case involves attempting to log perpetually changing data while avoiding console-bloat, then one way to achieve this (in certain browsers) would be to use console.clear() before each output.如果您的用例涉及尝试记录永久更改的数据同时避免控制台膨胀,那么实现此目的的一种方法(在某些浏览器中)是在每次输出之前使用console.clear()

 function writeSingleLine (msg) { console.clear(); console.log(msg); } writeSingleLine('this'); setTimeout( function () { writeSingleLine('is'); }, 1000); setTimeout( function () { writeSingleLine('a'); }, 2000); setTimeout( function () { writeSingleLine('hack'); }, 3000);

Note that this would probably break any other logging functionality that was taking place within your application.请注意,这可能会破坏应用程序中发生的任何其他日志记录功能。

Disclaimer: I would class this as a hack.免责声明:我会将其归类为黑客。

If your only purpose to stop printing on many lines, One way is to group the values if you don't want them to fill your complete console如果您停止多行打印的唯一目的,一种方法是将值分组,如果您不希望它们填满整个控制台

PS:- See you browser console for output PS:-见你的浏览器控制台输出

 let arr = new Array(10).fill(0) console.groupCollapsed('index') arr.forEach((val,index) => { console.log(index) }) console.groupEnd()

console.group 控制台组

console.groupCollapsed console.groupCollapsed

Something about @shennan idea:关于@shennan 的想法:

 function init(poolSize) { var pool = []; console._log = console.log; console.log = function log() { pool.push(arguments); while (pool.length > poolSize) pool.shift(); draw(); } console.toLast = function toLast() { while (pool.length > poolSize) pool.shift(); var last = pool.pop() || []; for (var a = 0; a < arguments.length; a++) { last[last.length++] = arguments[a]; } pool.push(last); draw(); } function draw() { console.clear(); for(var i = 0; i < pool.length; i++) console._log.apply(console, pool[i]); } } function restore() { console.log = console._log; delete console._log; delete console.toLast; } init(3); console.log(1); console.log(2); console.log(3); console.log(4); // 1 will disappeared here console.toLast(5); // 5 will go to row with 4 restore();

collect your output in an array and then use join function with a preferred separator将您的输出收集在一个数组中,然后使用带有首选分隔符的连接函数

function echo(name, num){
    var ar= [];
    for(var i =0;i<num;i++){
        ar.push(name);
    }
    console.log(ar.join(', '));
}

echo("apple",3)

check also Array.prototype.join() for mode details检查Array.prototype.join()以获取模式详细信息

var elements = ['Fire', 'Wind', 'Rain'];

console.log(elements.join());
// expected output: Fire,Wind,Rain

console.log(elements.join(''));
// expected output: FireWindRain

console.log(elements.join('-'));
// expected output: Fire-Wind-Rain

A simple solution using buffered output.使用缓冲输出的简单解决方案。 Works with deno and should work with node .适用于deno并且应该适用于node (built for porting pascal console programs to javascript) (专为将 pascal 控制台程序移植到 javascript 而构建)

const write = (function(){
    let buffer = '';
    return function (text='\n') {
        buffer += text;
        let chunks = buffer.split('\n');
        buffer = chunks.pop();
        for (let chunk of chunks)
            {console.log(chunk);}
    }
})();

function writeln(text) { write(text + '\n'); }

To flush the buffer, you should call write() at the end of program.要刷新缓冲区,您应该在程序结束时调用write() If you mix this with console.log calls, you may get garbage ouput.如果您将其与console.log调用混合使用,您可能会得到垃圾输出。

You can use a spread operator to display output in the single line.您可以使用扩展运算符在单行中显示输出。 The new feature of javascript ES6. javascript ES6 的新特性。 see below example见下面的例子

   for(let i = 1; i<=10; i++){
        let arrData = [];
        for(let j = 1; j<= 10; j++){
            arrData.push(j+"X"+i+"="+(j*i));
        }
        console.log(...arrData);
    }

That will print 1 to 10 table in single line.这将在一行中打印 1 到 10 个表。

if you want for example console log array elements without a newline you can do like this如果你想要例如没有换行符的控制台日志数组元素,你可以这样做

const arr = [1,2,3,4,5];

Array.prototype.log = (sep='') => {
    let res = '';
    for(let j=0; j<this.lengthl j++){
        res += this[j];
        res += sep;
    }
    console.log(res);
}

// console loging

arr.log(sep=' '); // result is: 1 2 3 4 5 

Useful for debugging or learning what long chained maps are actually doing.用于调试或学习长链映射实际在做什么。

let myConsole = (function(){
    let the_log_buffer=[[]], the_count=0, the_single_line=false;
    const THE_CONSOLE=console, LINE_DIVIDER='  ~  ', ONE_LINE='ONE_LINE',     
          PARAMETER_SEPARATOR= ', ', NEW_LINE = Symbol();
          
    const start = (line_type='NOT_ONE_LINE') => {
        the_log_buffer=[[]];
        the_count=0;
        the_single_line = line_type == ONE_LINE;   
        console = myConsole;  
    }
    const stop = () =>  {
        isNewline();
        console = THE_CONSOLE; 
    };                          
    const isNewline = a_param => {
        if (the_single_line && a_param==NEW_LINE) return;
        const buffer_parts = the_log_buffer.map(one_set=> one_set.join(PARAMETER_SEPARATOR))
        const buffer_line = buffer_parts.join(LINE_DIVIDER);    
        if (the_single_line) {                           
          THE_CONSOLE.clear();
        }
        THE_CONSOLE.log( buffer_line ); 
        the_log_buffer = [[]];
        the_count=0;
    }
    const anObject = an_object => {            
        if (an_object instanceof Error){
            const error_props = [...Object.getOwnPropertyNames(an_object)];
            error_props.map( error_key => an_object['_' + error_key] = an_object[error_key] );
        }
        the_log_buffer[the_count].push(JSON.stringify(an_object));
    }
    const aScalar = a_scalar => {
        if (typeof a_scalar === 'string' && !isNaN(a_scalar)) {
            the_log_buffer[the_count].push("'" + a_scalar + "'");
        } else {
            the_log_buffer[the_count].push(a_scalar);
        }
    }
    const notNewline = a_param => typeof a_param === 'object' ? anObject(a_param):aScalar(a_param);
    const checkNewline = a_param => a_param == NEW_LINE ? isNewline(a_param) : notNewline(a_param);
    const log = (...parameters_list) => {   
        the_log_buffer[the_count]=[];
        parameters_list.map( checkNewline );
        if (the_single_line){
            isNewline(undefined);
        }else{
            const last_log = parameters_list.pop();
            if (last_log !== NEW_LINE){
                the_count++;
            }
        }
    }
    return Object.assign({}, console, {start, stop, log, ONE_LINE, NEW_LINE});
})();

function showConcatLog(){
    myConsole.stop();
    myConsole.start();
    console.log('a');
    console.log('bb');  
    console.dir({i:'not', j:'affected', k:'but not in step'})
    console.log('ccc');
    console.log([1,2,3,4,5,'6'], {x:8, y:'9'});
    console.log("dddd", 1, '2', 3, myConsole.NEW_LINE);
    console.log("z", myConsole.NEW_LINE, 8, '7');
    console.log(new Error("error test"));
    myConsole.stop();
}

myConsole.start(myConsole.ONE_LINE);
var stop_callback = 5;
function myCallback(){
    console.log(stop_callback, 'Date.now()', myConsole.NEW_LINE, Date.now());
    stop_callback--;
    if (stop_callback>0){
        window.setTimeout(myCallback, 1000);
    }else{
        showConcatLog();
    }
}       
window.setTimeout(myCallback, 1000);
// Source code for printing 2d array
window.onload = function () {
    var A = [[1, 2], [3, 4]];
    Print(A);
}

function Print(A) {
    var rows = A.length;
    var cols = A[0].length;
    var line = "";
    for (var r = 0; r < rows; r++) {
        line = "";
        for (var c = 0; c < cols; c++) {
            line += A[r][c] + " ";
        }
        console.log(line);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM