console.log的非易失性替代品

non-volatile substitute for console.log

本文关键字:易失性 替代品 log console      更新时间:2023-09-26

我发现自己经常被console.log()绊倒,因为它是异步的。

我的意思是,它倾向于不捕捉变量在特定时间点的值。

它适用于简单值,因为赋值给具有立即值的变量会将变量绑定到一个全新的对象。,例如

var x = 3;
console.log(x);  //prints 3
x=4; 

但当你开始处理通过引用绑定的对象时,事情就会。。。与直觉相反。例如

var obj = {x: 3};
console.log(x); //prints 4!
obj.x = 4;

我是否可以使用其他一些日志记录函数,在调用代码时为我提供对象的状态?我正在寻找同步的东西,或者至少从它产生的结果来看是同步的。

如果它能跨平台运行,我会很高兴,但我很高兴能得到一个在chrome中运行的。

根据要求,总结:

对于简单的、可串行的对象,console.log(JSON.stringify(x))工作得很好:

var x = { foo: 17, bar: "quux" };
console.log(JSON.stringify(x))
// => {"foo":17,"bar":"quux"}

对于HTML元素,console.log(x.outerHTML)运行良好。

var x = document.getElementsByTagName('p');
console.log(Array.prototype.map.call(x, function(e) {
  return e.outerHTML;
}));
// => ["<p>foo</p>", "<p id="bar">bar</p>"]
<p>foo</p>
<p id="bar">bar</p>

如果对象不可串行化,您可能需要深入研究它们并提取可串行化的部分:

var x = { content: { foo: 17, bar: "quux" } };
x.self = x;
console.log(JSON.stringify(x.content));
// => {"foo":17,"bar":"quux"}

如果这些技巧都不适用,您可能需要深度克隆对象(这个答案给出了我在下面使用的一个非常好的clone函数,以及许多注意事项):

function clone(item) {
    if (!item) { return item; } // null, undefined values check
    var types = [ Number, String, Boolean ], 
        result;
    // normalizing primitives if someone did new String('aaa'), or new Number('444');
    types.forEach(function(type) {
        if (item instanceof type) {
            result = type( item );
        }
    });
    if (typeof result == "undefined") {
        if (Object.prototype.toString.call( item ) === "[object Array]") {
            result = [];
            item.forEach(function(child, index, array) { 
                result[index] = clone( child );
            });
        } else if (typeof item == "object") {
            // testing that this is DOM
            if (item.nodeType && typeof item.cloneNode == "function") {
                var result = item.cloneNode( true );    
            } else if (!item.prototype) { // check that this is a literal
                if (item instanceof Date) {
                    result = new Date(item);
                } else {
                    // it is an object literal
                    result = {};
                    for (var i in item) {
                        result[i] = clone( item[i] );
                    }
                }
            } else {
                // depending what you would like here,
                // just keep the reference, or create new object
                if (false && item.constructor) {
                    // would not advice to do that, reason? Read below
                    result = new item.constructor();
                } else {
                    result = item;
                }
            }
        } else {
            result = item;
        }
    }
    return result;
}
var el = document.querySelector('p');
x = { el: el, content: { foo: 17, bar: "quux" } };
console.log("el.attributes[0]: changed", x);
console.log("el.attributes: empty", clone(x));
el.setAttribute('changed', 'true');
<p>foo</p>

在最坏的情况下,您可以随时暂停执行:

var el = document.querySelector('p');
for (var i = 0; i < 1000; i++) {
  el.textContent = "Iteration #" + i;
  // check 458th iteration:
  if (i == 458) {
    console.log("Accurate:", el);
    debugger;
    console.log("Not accurate:", el);
  }
}
<p></p>

使用JSON串行化或深度复制的另一种可能性是使用Node的inspect进行串行化。我已经制作了一个端口(inspect-x),它可以完成90%的浏览器工作(并非所有功能都可以在浏览器中实现)。

var inspect = returnExports;
var x = {
  foo: 17,
  bar: 'quux',
  arr: [1,'2', undefined, null, false],
  fum: function blah() {},
  fee: new ArrayBuffer(4),
  woo: new Date(),
  wee: /match/gi,
  wiz: 1,
  poo: true,
  pee: Object('hi'),
  jqu: $(document.body),
  ppp: document.getElementsByTagName('pre')
};
document.getElementById('out').appendChild(document.createTextNode(inspect(x, {showHidden: true})));
console.log(inspect(x, {showHidden: true}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.3.1/es5-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.3.1/es5-sham.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<script src="https://rawgit.com/Xotic750/inspect-x/master/lib/inspect-x.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<pre id="out"></pre>

您可以将其与JSON.stringify 进行比较

var inspect = returnExports;
var x = {
  foo: 17,
  bar: 'quux',
  arr: [1,'2', undefined, null, false],
  fum: function blah() {},
  fee: new ArrayBuffer(4),
  woo: new Date(),
  wee: /match/gi,
  wiz: 1,
  poo: true,
  pee: Object('hi'),
  jqu: $(document.body),
  ppp: document.getElementsByTagName('pre')
};
document.getElementById('out').appendChild(document.createTextNode(JSON.stringify(x, null, 2)));
console.log(JSON.stringify(x, null, 2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.3.1/es5-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.3.1/es5-sham.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<pre id="out"></pre>

正如您所看到的,inspect提供了更多的信息,并且可以针对更大的深度进行配置。