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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:04:02  来源:igfitidea点击:

Javascript TRUE is not defined or in quotes

javascriptjquery

提问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 TRUEas a value / expression. There is no value TRUEnatively defined in javascript. There is truebut javascript is case sensitive so it won't bind TRUEto true.

如果没有引号,javascript 将尝试解释TRUE为值/表达式。TRUEjavascript 中没有本机定义的值。有true但是 javascript 区分大小写,所以它不会绑定TRUEtrue.

The value you get back from text()is a stringprimitive. 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 trueand falseare lower case.

JavaScript 布尔值truefalse小写。

回答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

TRUErefers to a variable named TRUEwhich doesn't exist, so you get an error. "TRUE"is a string containing the characters TRUE. Your variable servicewill 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 = '';
}

Difference between == and === in JavaScript

JavaScript 中 == 和 === 的区别

回答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(它区分大小写,就像语言中的其他所有内容一样)。