问题描述
我正在尝试Monaco(用于Web的VSCode IDE)。目的是打印用户编写的代码的输出。前用户键入console.log("123")
,然后我想获取“ 123”作为输出。我该如何实现?任何正则表达式或类似的解决方案都是不好的。我需要代码的实际输出:
const run = () => {
const model = monaco.current.editor.getModel()
const value = model.getValue() // Value is console.log("123")
var code = new Function(value)
var code2 = eval(value) //logs "123"
console.log(code) //logs ƒ anonymous({console.log("123")}
console.log(code2) //logs undefined
const output = ?
}
<MonacoEditor
ref={monaco}
width="800"
height="600"
language="javascript"
theme="vs-dark"
value={code}
options={options}
onChange={code => setCode(code)}
/>
在此示例中,如何将const output
设置为“ 123”?
或仅从此代码段获取“ 123”作为输出
var s = "console.log(123)"
alert(s)
解决方法
var s = "console.log(123)"
alert(eval(s))
在上述情况下,将执行console.log
代码,并在控制台中完成日志记录,但是警报中的值将为undefined
,因为{{1}的返回值}是console.log
。例如:
undefined
这里记录已完成,但是const val = console.log('test');
的值为val
。并且您正在Alert语句中使用此值。
要实现所需的功能,可以按如下所示覆盖日志记录功能:
undefined
,
您不能使用默认的console.log功能来做到这一点。您需要修改它。试试这个
console.tempLog = console.log;
console.log = function(value)
{
console.tempLog(value);
return value;
};
const output = eval('console.log("123")');
在这里,我创建了console.tempLog以避免递归循环!希望这会有所帮助!