ruby 将 console.log 值分配给变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15462122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:49:47  来源:igfitidea点击:

Assign console.log value to a variable

javascriptrubyconsole.loglanguage-comparisons

提问by Dru

How can I assign a JavaScript object to a variable which was printed using console.log?

如何将 JavaScript 对象分配给使用 打印的变量console.log

I am in Chrome console. With Ruby I would use test = _to access the most recent item printed.

我在 Chrome 控制台中。使用 Ruby 我会test = _用来访问最近打印的项目。

采纳答案by mirrormx

You could override standard console.log()function with your own, adding the behaviour you need:

您可以console.log()使用自己的功能覆盖标准功能,添加您需要的行为:

console.oldLog = console.log;

console.log = function(value)
{
    console.oldLog(value);
    window.$log = value;
};

// Usage

console.log('hello');

$log // Has 'hello' in it

This way, you don't have to change your existing logging code. You could also extend it adding an array and storing the whole history of printed objects/values.

这样,您就不必更改现有的日志记录代码。您还可以扩展它添加一个数组并存储打印对象/值的整个历史记录。

回答by Nick Brady

If you want to do this to an object that has been already logged (one time thing), chrome console offers a good solution.

如果您想对已记录的对象执行此操作(一次性),chrome 控制台提供了一个很好的解决方案。

Hover over the printed object in the console, right click, then click on "Store as Global Variable". Chrome will assign it to a temporary var name for you which you can use in the console.

将鼠标悬停在控制台中的打印对象上,右键单击,然后单击“存储为全局变量”。Chrome 将为您分配一个临时变量名称,您可以在控制台中使用该名称。

enter image description here

在此处输入图片说明

回答by Stewie

In Chrome developer tools, you may access last item by $_:

在 Chrome 开发者工具中,您可以通过$_以下方式访问最后一项:

> 1+1;
  2
> $_
  2

回答by mattk

Derivative of mirrormx's answer, but more convenient. I don't need to write a function and can just put it in anywhere on the spur of the moment.

mirrormx 答案的衍生物,但更方便。我不需要编写一个函数,可以一时冲动把它放在任何地方。

console.log(window.$log = data);

回答by kirugan

Here is chrome referencefor comand line api. There is $_ variable but it "Returns the value of the most recently evaluated expression" not printed, you can make your own log function like this:

这是命令行 api 的chrome 参考。有 $_ 变量,但它“返回最近评估的表达式的值”未打印,您可以像这样制作自己的日志函数:

function log(data){
   console.log(data);
   return data;
}
// after that you can access last printed value by $_

Please, note that my function is for example, console.log possibilities is much more advanced

请注意,我的功能是例如,console.log 的可能性要高级得多