将空字符串分配给 javascript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31602077/
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-23 06:54:08  来源:igfitidea点击:

Assign empty string to javascript variable

javascript

提问by Vetri Manoharan

I get return value as null and assign that value it shows as null in the UI. But I want to check some condition and if it is null, it should not show up anything.. I tried the below code and it doesn't work

我将返回值设为 null 并分配该值,它在 UI 中显示为 null。但我想检查一些条件,如果它为空,它不应该显示任何东西..我尝试了下面的代码,但它不起作用

var companyString;
if(utils.htmlEncode(item.companyname) == null)
{
  companyString = '';
}
else{
  companyString = utils.htmlEncode(item.companyname);
}

采纳答案by user2864740

Compare item.companynameto null (but probably really any false-y value) - and notthe encoded form.

比较item.companyname为null(但可能确实存在任何虚假记载,Y值) -和编码形式。

This is because the encoding will turn nullto "null"(or perhaps "", which are strings) and "null" == null(or any_string == null) is false.

这是因为编码会变成null"null"(或者也许"",这是字符串)和"null" == null(或any_string == null)是假的。

Using the ternary operator it can be written as so:

使用三元运算符可以这样写:

var companyString = item.companyname
  ? utils.htmlEncode(item.companyname)
  : "";

Or with coalescing:

或合并:

var companyString = utils.htmlEncode(item.companyname ?? "");

Or in a long-hand form:

或者以长手形式:

var companyString;
if(item.companyname) // if any truth-y value then encode
{
  companyString = utils.htmlEncode(item.companyname);
}
else{                // else, default to an empty string
  companyString = '';
}

回答by Panther

var companyString;
if(item.companyname !=undefined &&   item.companyname != null ){
companyString = utils.htmlEncode(item.companyname);  
}
else{
companyString = '';
}

Better to check not undefinedalong with not nullin case of javascript. And you can also put alertor console.logto check what value you are getting to check why your if block not working. Also, utls.htmlEncode will convert your nullto String having null literal, so compare without encoding.

最好not undefinednot nulljavascript一起检查。你也可以输入alertconsole.log检查你得到的值来检查为什么你的 if 块不起作用。此外,utls.htmlEncode 会将您null的字符串转换为具有 的字符串null literal,因此无需编码即可进行比较。

回答by AkshayJ

var companyString="";
if(utils.htmlEncode(item.companyname) != null)
{
   companyString = utils.htmlEncode(item.companyname);
}