JavaScript 解析引号中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11241362/
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
JavaScript parse variable in quote
提问by siaooo
Possible Duplicate:
JavaScript Variable inside string without concatenation - like PHP
In PHP, double quotes has the ability to read variable, e.g.
在 PHP 中,双引号具有读取变量的能力,例如
"$foo"
But in JavaScript, you have to always use a +
to read a variable so that the variable won't be inside the quote when it is read, e.g.
但是在 JavaScript 中,您必须始终使用 a+
来读取变量,以便在读取时变量不会在引号内,例如
var foo='bar';
alert("The name's "+foo);
So, is there any workaround or method to do this? Using +
all the time is quite troublesome.
那么,是否有任何解决方法或方法可以做到这一点?一直使用+
还是挺麻烦的。
采纳答案by Blaster
Nope, that's not possible in JavaScript.
不,这在 JavaScript 中是不可能的。
In JavaScript, variables are turned into string when put in single quotes or doubles quotes and can't be parsed. In JavaScript everything inside quotes is treated as string.
在 JavaScript 中,变量放在单引号或双引号中时会变成字符串,无法解析。在 JavaScript 中,引号内的所有内容都被视为 string。
Even if you write custom parser, you will have no way to figure out if something in quotes is really a variable or an string because a variable named name
can also appear in string somewhere which will create naming collisions.
即使您编写自定义解析器,您也无法确定引号中的内容是否真的是变量或字符串,因为命名的变量name
也可能出现在字符串中的某处,这会产生命名冲突。