如何在Chrome或Firefox的JavaScript控制台中引用最后一个打印出来的对象

How to refer to the last print out Object in JavaScript console of Chrome or Firefox?

本文关键字:最后一个 引用 打印 对象 JavaScript Chrome Firefox 控制台      更新时间:2023-09-26

有没有一种方法可以引用您最喜欢的浏览器的JavaScript控制台中刚刚打印出来的最后一个对象?

例如,在您的代码中,JavaScript函数末尾有一个console.log(myObject)。有没有可能在控制台中引用这个打印出来的myObject,在控制台中基于这个对象进行一些测试?

实际示例。。。

JavaScript文件中的代码:

console.log("Test");

哪个打印Test

现在我想做一些事情,比如console.last().substring(0,2),它应该打印Te

不,这在标准console API中是不可能的。然而,您可以围绕console.log()编写自己的包装器,它提供以下内容:

var _log = console.log;
console.log = function () {
    // turn arguments into an array and store it
    this._last = [].slice.call(arguments);
    // call the original function
    _log.apply(console, arguments);
};
console.last = function() {
    return this._last;
};

请注意,console.last()的此实现将始终返回一个数组,因为console.log()接受任意数量的参数:

> console.log('foo', 3, true)
  foo 3 true
> console.last()
  ["foo", 3, true]