开发者

Javascript TRUE is not defined or in quotes

I have a XML file that contains

<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")

var service = tis.find("service").text();

if(service === TRUE){
    var service_tag = '<a title="Service" href="">Servi开发者_StackOverflow中文版ce</a>'
} else {
    var service_tag = '';
}


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.

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


JavaScript boolean true and false are lower case.


Set service equal to this, so JavaScript will be able to interpret your values:

var service = tis.find("service").text().toLowerCase(); 


its because the tripe equal also check for type, and TRUE it's a identifier "TRUE" is a value

// this will work
if(service === "TRUE"){
    var service_tag = '<a title="Service" href="">Service</a>'
} else {
    var service_tag = '';
}

Difference between == and === in JavaScript


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).


var service = tis.find("service").text();

This returns a string "TRUE". Since === checks for the type as well, it always returns false.


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.


I had this error because I quickly typed it with typo

someBooleanVar === ture

this is wrong

it should be true not ture

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜