Javascript TRUE 未定义或在引号中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7650926/
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 TRUE is not defined or in quotes
提问by John Magnolia
I have a XML file that contains
我有一个 XML 文件,其中包含
<car>
<id>123</id>
<sunroof>FALSE</sunroof>
<service>TRUE</service>
</car>
The following code only works if I wrap TRUE inside quotes e.g (service == "TRUE")
以下代码仅在我将 TRUE 包裹在引号内时才有效,例如 (service == "TRUE")
var service = tis.find("service").text();
if(service === TRUE){
var service_tag = '<a title="Service" href="">Service</a>'
} else {
var service_tag = '';
}
回答by JaredPar
Without quotes javascript will try to interpret TRUE
as a value / expression. There is no value TRUE
natively defined in javascript. There is true
but javascript is case sensitive so it won't bind TRUE
to true
.
如果没有引号,javascript 将尝试解释TRUE
为值/表达式。TRUE
javascript 中没有本机定义的值。有true
但是 javascript 区分大小写,所以它不会绑定TRUE
到true
.
The value you get back from text()
is a string
primitive. Writing "TRUE"
gives you back the string
"TRUE"
which does compare succesfully with the value service
你从中得到的值text()
是一个string
原始值。写作"TRUE"
会返回string
"TRUE"
与价值比较成功的那个service
回答by MeLight
JavaScript boolean true
and false
are lower case.
JavaScript 布尔值true
和false
小写。
回答by WEFX
Set service equal to this, so JavaScript will be able to interpret your values:
将 service 设置为与此相等,以便 JavaScript 能够解释您的值:
var service = tis.find("service").text().toLowerCase();
回答by Sajith Nair
var service = tis.find("service").text();
This returns a string "TRUE". Since === checks for the type as well, it always returns false.
这将返回一个字符串“TRUE”。因为 === 也会检查类型,所以它总是返回 false。
回答by Andrew Wilkinson
TRUE
refers to a variable named TRUE
which doesn't exist, so you get an error. "TRUE"
is a string containing the characters TRUE
. Your variable service
will contain a string, so the second of these are what you want.
TRUE
引用一个TRUE
不存在的命名变量,所以你会得到一个错误。"TRUE"
是一个包含字符的字符串TRUE
。您的变量service
将包含一个字符串,因此其中的第二个就是您想要的。
回答by Roberto Alarcon
its because the tripe equal also check for type, and TRUE it's a identifier "TRUE" is a value
它是因为牛肚等于也检查类型,并且 TRUE 它是一个标识符“TRUE”是一个值
// this will work
if(service === "TRUE"){
var service_tag = '<a title="Service" href="">Service</a>'
} else {
var service_tag = '';
}
回答by Quentin
This is expected.
这是预期的。
tis.find("service").text();
returns a string, not a boolean, and the JavaScript boolean for truth is true
(which is case sensitive, like everything else in the language).
tis.find("service").text();
返回一个字符串,而不是一个布尔值,并且 JavaScript 布尔值是true
(它区分大小写,就像语言中的其他所有内容一样)。