最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to check if a variable is empty in JavaScript? - Stack Overflow

programmeradmin1浏览0评论
var characterName = document.getElementById("pilotName").value;
var characterID = 0;
var charSecStatus = 0;
var corpName = " ";
var allianceName = " ";


//callback
makeRequest('.xml.aspx?names=' + characterName, function() {
  if (xmlhttp.status == OK_RESPONSE) {

    //read character info
    characterID = xmlhttp.responseXML.getElementsByTagName("row")[0].getAttribute("characterID");

    makeRequest('.xml.aspx?characterID=' + characterID, function() {

      if (xmlhttp.status == OK_RESPONSE) {

        //read character info 
        characterID = xmlhttp.responseXML.getElementsByTagName("characterID")[0].innerHTML;
        charSecStatus = xmlhttp.responseXML.getElementsByTagName("securityStatus")[0].innerHTML;
        corpName = xmlhttp.responseXML.getElementsByTagName("corporation")[0].innerHTML;
        allianceName = (xmlhttp.responseXML.getElementsByTagName("alliance")[0] || {
          innerHTML: ""
        }).innerHTML;
      }
    });
  }
});

(partial code pictured, no bracketspam pls) I'm trying to check if the "alliance" variable is empty because certain '"corp" are not in "alliances" and it would be critical error on website if it tried to display an empty variable, so is there a way to check if allianceName is empty after retrieving it from the XML tree and setting it to like "No Alliance" if it IS empty? Thanks

var characterName = document.getElementById("pilotName").value;
var characterID = 0;
var charSecStatus = 0;
var corpName = " ";
var allianceName = " ";


//callback
makeRequest('https://api.eveonline./eve/CharacterID.xml.aspx?names=' + characterName, function() {
  if (xmlhttp.status == OK_RESPONSE) {

    //read character info
    characterID = xmlhttp.responseXML.getElementsByTagName("row")[0].getAttribute("characterID");

    makeRequest('https://api.eveonline./eve/CharacterInfo.xml.aspx?characterID=' + characterID, function() {

      if (xmlhttp.status == OK_RESPONSE) {

        //read character info 
        characterID = xmlhttp.responseXML.getElementsByTagName("characterID")[0].innerHTML;
        charSecStatus = xmlhttp.responseXML.getElementsByTagName("securityStatus")[0].innerHTML;
        corpName = xmlhttp.responseXML.getElementsByTagName("corporation")[0].innerHTML;
        allianceName = (xmlhttp.responseXML.getElementsByTagName("alliance")[0] || {
          innerHTML: ""
        }).innerHTML;
      }
    });
  }
});

(partial code pictured, no bracketspam pls) I'm trying to check if the "alliance" variable is empty because certain '"corp" are not in "alliances" and it would be critical error on website if it tried to display an empty variable, so is there a way to check if allianceName is empty after retrieving it from the XML tree and setting it to like "No Alliance" if it IS empty? Thanks

Share Improve this question edited Jan 7, 2021 at 22:22 simhumileco 34.7k17 gold badges147 silver badges123 bronze badges asked Feb 10, 2016 at 4:08 timoxazerotimoxazero 411 gold badge1 silver badge2 bronze badges 5
  • 1 Possible duplicate of How do you check for an empty string in JavaScript? – PM 77-1 Commented Feb 10, 2016 at 4:11
  • Those answers will not work. The allianceName variable he gave was given a non-empty value " ". In this case, the value of that variable is actually true. A string with whitespace characters has a true value – Richard Hamilton Commented Feb 10, 2016 at 4:16
  • @RichardHamilton so I need to initialize it as var allianceName = ""? – timoxazero Commented Feb 10, 2016 at 4:19
  • yep, it's a mon mistake in JavaScript – Richard Hamilton Commented Feb 10, 2016 at 4:19
  • @timoxazero—you don't need to initialise it at all, just declare it and it will be given a value of undefined, which is falsey. – RobG Commented Feb 10, 2016 at 4:31
Add a ment  | 

4 Answers 4

Reset to default 3

You are declaring true variables here

var corpName = " ";
var allianceName = " "

In JavaScript, the value of a string with whitespace characters is actually truthy. While the above values do look empty, the reality is they're not. Try it out yourself.

Boolean(" ");
=> true

To set these variables empty, you need to declare them without whitespace characters

var corpName = "";
var allianceName = "";

After you have this, there are two ways to check if the variable is empty

if (!corpName || !corpName.length)

Assuming, you did accidentally include the whitespace character, there are several ways to fix this. We can modify these strings in these cases.

Boolean(" ".trim());
=> false

In the above example, the trim() function is used to remove whitespace characters from a string.

You could also search the string for non-whitespace characters

/\S/.test(" ")
=> false

The \S modifier finds all non whitespace characters.

Alternatively, you could also use the replace function

Boolean(" ".replace(/\s/g, ''));

The global flag g finds all references to the previous regular expression.

If you just want to check whether there's any value in a variable, then try this,

if (str) {
    //do something
}

or,

//when undefined
if (typeof str == 'undefined'){
//do something
}

If you need to check specifically for an empty string over null, then, try this.

//when defined, but empty
if ((str.length == 0)||(str== ""))
{
//do something
}

You can try something like this:

Note: If you value is null or undefined, !value?true:false should work. Also value.length is also good approach but should be used in case of string. If value is number, value.length will return 0, i.e. true for empty check.

function isEmpty(value) {
  switch (typeof(value)) {
    case "string": return (value.length === 0);
    case "number":
    case "boolean": return false;
    case "undefined": return true;
    case "object": return !value ? true : false; // handling for null.
    default: return !value ? true : false
  }
}

var a = " ";
console.log(a, "is empty:", isEmpty(a))
console.log(a, "is empty:", isEmpty(a.trim()))

a = 0;
console.log(a, "is empty:", isEmpty(a))

a = undefined;
console.log(a, "is empty:", isEmpty(a))

a = null;
console.log(a, "is empty:", isEmpty(a))

Also, you can change

allianceName = (xmlhttp.responseXML.getElementsByTagName("alliance")[0] || {
   innerHTML: "
}).innerHTML;

to

allianceName = xmlhttp.responseXML.getElementsByTagName("alliance")[0].innerHTML || "";

I believe in JavaScript there's a function called isset() which takes one argument and returns true if it is set to a value and false if it is not.

发布评论

评论列表(0)

  1. 暂无评论