最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Put a value in webkit console from console.log into a variable - Stack Overflow

programmeradmin2浏览0评论

If there is an output in the chrome/safari webkit inspector containing an object that prints out such as:

Only much more plicated with loads of nested objects (which is why a copy/paste wont do)

Is there a way to put this in a variable to inspect in further and process it after its been printed on the console (its printed via console.log), just only after its already in the console?

If there is an output in the chrome/safari webkit inspector containing an object that prints out such as:

Only much more plicated with loads of nested objects (which is why a copy/paste wont do)

Is there a way to put this in a variable to inspect in further and process it after its been printed on the console (its printed via console.log), just only after its already in the console?

Share Improve this question asked Mar 17, 2013 at 18:48 TarangTarang 76k39 gold badges219 silver badges279 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

$_ will give you last output of console. So in console you can assign in to a variable.

Note that you can do this only in console and not from your own code.

Here's a way to do it without wrapping console.log in a custom log function:

var justLogged;
var oldLog = console.log;

console.log = function () {
    oldLog.apply(console, arguments);
    justLogged = arguments;
};

console.log('test');

// if necessary, restore console.log to its original behavior when you're finished with it
console.log = oldLog;

The value of justLogged will be ['test'], since you just logged it.

If you're looking to get the last output, do as Mohsen suggests.

If you're trying to get the last output of console.log, your best bet is a wrapper function. This can (1) do what you want (2) easily be disabled in production, which is helpful on old IE and hides debug messages.

var log = (function() {
    var lastOutput;
    var fn = function() {
        lastOutput = arguments[0];              // save the last argument
        console.log.apply(console, arguments);  // defer to console.log
    };
    fn.last = function() {
        return lastOutput;
    };
    return fn;
})();

log("abc123");
log.last();     // => "abc123"
发布评论

评论列表(0)

  1. 暂无评论