简体   繁体   中英

How to convert boolean true or false into 1 Or 0 in javascript

function getReadyStateHandler(xmlHttpRequest) {
  return function() {
    if (xmlHttpRequest.readyState == 4) {
      if (xmlHttpRequest.status == 200) {
        var jsonString = xmlHttpRequest.responseText;
        var jsonObject = (new Function("return " + jsonString))();
        var exportVal = jsonObject.exportValue;
      }
    }
  }
}

This is javascript code.it returns true and false value but i want to print 1 and 0.How to solve this problem,please help me.

function getReadyStateHandler(xmlHttpRequest) {
    return function() {
        if (xmlHttpRequest.readyState == 4) {
            if (xmlHttpRequest.status == 200) {
                var jsonString = xmlHttpRequest.responseText;
                var jsonObject = (new Function("return " + jsonString))();

                var accountid = jsonObject.accountid;

                var exportVal = +jsonObject.exportValue;

                if (accountid.length > 0) {

                    dispTable(accountid, exportVal);

                } 


        }
    };
}

function dispTable(accountid,exportVal) {

    $("#tbl tbody tr").eq(0).remove(); 

    for (var i = 0; i < accountid.length; i++) {
        var temp = parseInt(i) + 1;
        $('#tbl > tbody:last')
                .append(
                        '<tr>' + "<td class='numeric'>"+ temp+ "</td>"
                                + "<td class='numeric'>"+ accountid[i]+ "</td>"
                                + "<td class='numeric'>"+ exportVal[i]+ "</td>"
                                + "<td  class='numeric'>"


    }


}

This is my new code.in which i have displayed the table in which value is displayed as true and false.

You can use + sign:

var myVar = true;
myVar = +myVar; // 1

myVar = false;
myVar = +myVar; // 0

So if your jsonObject.exportValue is boolean you can just convert it by:

var exportVal = +jsonObject.exportValue;

Simply, use Number Function

var s = false;
alert(Number(s));

For your requirement,

 var exportVal = Number(jsonObject.exportValue);

您可以尝试使用三元运算符,例如:

var yourreturnValue = result ? 1 : 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM