javascript - `"\n"` can't run in `new Function()`
问题描述
I want to run code dynamiclly, without using <script>
,so I used new Function
,but there is a problem when I write \n
:
function run (code) {
(new Function(code))()
}
run('console.log("run well")') // it work well
run('console.log("\nError")') // error
the result is: error
Uncaught SyntaxError: Invalid or unexpected token
at new Function (<anonymous>)
at run (<anonymous>:2:3)
at <anonymous>:1:1
And we can find the reason in console: the '\n' has been turn to a new line
(function() {
console.log(" // error here
Error")
})
so using ` to replace " can solve this problem:
run(`console.log("\nWell")`)
(function() {
console.log(` // work here
Error`)
})
but it is not suitable that using ` in production, so if there other way to let it well done ?
解决方案
由于函数体是字符串,\n
实际上会被转换为换行符。您需要使用\\n
.
function run(code) {
(new Function(code))()
}
run('console.log("run well")') // it work well
run('console.log("\\nError")') // error
推荐阅读
- python - 如果 else 在 Python 中引发错误,则内联分配
- c++builder - 将 TIdString 转换为 AnsiString
- java - 为什么我的 java 渲染引擎没有更新窗口?
- python - Google Analytics API 和服务帐户身份验证
- javascript - 我正在制作一个获取请求,其目标是将坐标返回给一个对象,但它不起作用
- javascript - 如何从 youtube 制作视频
- python-3.x - Docker - pip install from requirements or copy installed modules
- ethereum - 路由器 pancakeswap v2 中的 TransferFrom 失败
- swift - 有没有办法通过 Swift 中的 Voiceover 使 Tilemap 的各个图块可访问和导航?
- ios - Swift:带有初始化程序的 TableView 返回 nil。尝试通过协议进行数据传递