如何从eval()获取console.log输出? [英] How to get console.log output from eval()?

查看:238
本文介绍了如何从eval()获取console.log输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 eval()从字符串运行脚本。下面是代码:

I am using eval() to run a script from a string. Below is the code:

eval('console.log( hello)');

我将从控制台输出中获得 hello 。我想知道是否可以将 hello 保存到当前上下文中的变量中。所以我正在寻找这样的东西:

I will get hello from the console output. I wonder whether I can save the hello into an variable in the current context. So I am looking for something like this:

const output = eval('console.log( hello)'); //我希望控制台输出是从 eval()函数返回的。

const output = eval('console.log("hello")'); // I expect the console output is returned from eval() function.

但是我得到了未定义响应。

推荐答案

这是不可能的,因为 console.log() 仅返回未定义,但是您可以使函数返回某些内容。

It is impossible because console.log() only returns undefined, however you can make a function that will return something.

示例:

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

const output = eval('console.log("hello")');

希望这会有所帮助。

这篇关于如何从eval()获取console.log输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆