首页 > 解决方案 > 使用 prompt() 时的不同输出

问题描述

与仅分配变量相比,为什么输出显示与提示不同?

迅速的:

var x = prompt(); // input "new \nline"
console.log(x); // output "new \nline"

分配变量:

var x = 'new \nline';
console.log(x) 
//output
new line

标签: javascript

解决方案


正如您在此处可用的 Mozilla 规范中看到的,提示消息将“字符串”作为输入,因此,如果您需要将转义字符“\”解析为字符串\\n而不是换行符\n,则将其解释为新行,您可以尝试以下操作:

var x = prompt(); // input "new \nline"
x = x.replace('\\n', '\n')
console.log(x);

输出:

new 
line

推荐阅读