Javascript null 或空字符串不起作用

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

Javascript null or empty string does not work

javascriptnull

提问by user2706372

I am trying to test that my string is null or empty, however it does not work.

我正在尝试测试我的字符串是否为空或空,但它不起作用。

My Code :

我的代码:

var veri = {
  YeniMusteriEkleTextBox: $('#MyTextbox').val(),
};

if (veri.YeniMusteriEkleTextBox === "" || 
    veri.YeniMusteriEkleTextBox == '' || 
    veri.YeniMusteriEkleTextBox.length == 0 || 
    veri.YeniMusteriEkleTextBox == null) {
  alert("Customer Name can not be empty!!!");
}

How can ? check YeniMusteriEkleTextBox is null or empty ?

怎么能 ?检查 YeniMusteriEkleTextBox 是 null 还是空?

回答by BenM

I would use the ! operator to test if it is empty, undefined etc.

我会用!运算符来测试它是否为空、未定义等。

if (!veri.YeniMusteriEkleTextBox) {
    alert("Customer Name can not be empty!!!");
}

Also you do not need the comma after YeniMusteriEkleTextBox: $('#MyTextbox').val(),

后面也不需要逗号 YeniMusteriEkleTextBox: $('#MyTextbox').val(),

Also testing for a length on an object that may be undefined will throw an error as the length will not be 0, it will instead be undefined.

此外,在可能未定义的对象上测试长度将引发错误,因为长度不会为 0,而是未定义。

回答by Alnitak

You need to .trimthe value to remove leading and trailing white space:

您需要.trim删除前导和尾随空格的值:

var veri = {
    YeniMusteriEkleTextBox: $('#YeniMusteriAdiTextbox_I').val().trim()
};

The .trimmethod doesn't exist on some older browsers, there's a shim to add it at the above MDN link.

.trim方法在某些较旧的浏览器上不存在,在上面的 MDN 链接中有一个 shim 可以添加它。

You can then just test !veri.YeniMusteriEkleTextBoxor alternatively veri.YeniMusteriEkleTextBox.length === 0:

然后您可以只测试!veri.YeniMusteriEkleTextBox或替代veri.YeniMusteriEkleTextBox.length === 0

if (!veri.YeniMusteriEkleTextBox) {
    alert("Customer Name can not be empty!!!");
}

回答by micha

You should use

你应该使用

if (!veri.YeniMusteriEkleTextBox) {

This also checks for undefinedwhich is not the same as null

这也检查undefined哪个与 null 不同

回答by mplungjan

Since no one else is suggestion $.trim, I will

由于没有其他人建议 $.trim,我会

Note I removed the trailing comma too and use the ! not operator which will work for undefined, empty null and also 0, which is not a valid customer name anyway

注意我也删除了尾随逗号并使用了!not 运算符适用于未定义、空 null 和 0,无论如何这都不是有效的客户名称

var veri = {
  YeniMusteriEkleTextBox: $.trim($('#MyTextbox').val())
};

if (!veri.YeniMusteriEkleTextBox) {
  alert("Customer Name can not be empty!!!");
}