在JavaScript中,有没有检查一个值不是null和空字符串的方法?我正在使用以下代码:
var data; //get its value from db
if(data != null && data != '') {
// do something
}
但我在想是否有另一个更好的解决方案。谢谢。
在JavaScript中,有没有检查一个值不是null和空字符串的方法?我正在使用以下代码:
var data; //get its value from db
if(data != null && data != '') {
// do something
}
但我在想是否有另一个更好的解决方案。谢谢。
如果您确实想要确认一个变量不是 null 且不是空字符串,那么您需要编写以下代码:
如果您确实希望确认一个变量不是 null 且不是空字符串,那么您可以编写以下代码:
如果你真的想确定一个变量既不为空也不是空字符串,你需要写:
if(data !== null && data !== '') {
// do something
}
请注意,我已更改您的代码以检查类型相等性( !== |
=== )。
然而,如果您只想确保代码仅对“合理”值运行,则可以像其他人已经指出的那样编写:
if (data) {
// do something
}
由于在JavaScript中,空值和空字符串都等于false(即
null == false
),因此这两个代码部分之间的区别在于,对于第一个部分,除了null或空字符串之外的每个值都将进入if
语句。但是,在第二个部分中,所有真值都将进入if
语句: false
,0
,null
,undefined
和空字符串将不会。
不要使用
if(data !== null && data !== '' && data!==undefined) {
// do something
}
你可以使用以下简单的代码if(Boolean(value)){
// do something
}
null
和空字符串在 JS 中都是 falsy 值。因此,
if (data) { ... }
但是需要注意的是:我会避免在代码中使用可能具有不同类型的变量。如果数据最终将是一个字符串,那么我会最初使用空字符串来定义我的变量,这样你就可以这样做:
完全足够。
if (data !== '') { ... }
没有空值(或任何奇怪的东西,如data = "0"
)干扰。
if (data?.trim().length > 0) {
//use data
}
?.
可选链操作符会通过短路并在数据为nullish(null或undefined)时返回undefined
,这会导致在if
表达式中被判定为false。
我经常测试真值和字符串中的空格:
if(!(!data || data.trim().length === 0)) {
// do something here
}
检查字符串是否为 undefined
或 null
或 ""
的简单方法:
const value = null;
if(!value) {
console.log('value is either null, undefined or empty string');
}
0
,false
。 - Bryce可以按照以下方式对 null 和空字符串进行验证:
<script>
function getName(){
var myname = document.getElementById("Name").value;
if(myname != '' && myname != null){
alert("My name is "+myname);
}else{
alert("Please Enter Your Name");
}
}
/**
* Test if the given value equals null or the empty string.
*
* @param {string} value
**/
const isEmpty = (value) => value === null || value === '';
// Test:
isEmpty(''); // true
isEmpty(null); // true
isEmpty(1); // false
isEmpty(0); // false
isEmpty(undefined); // false
试一下----------
function myFun(){
var inputVal=document.getElementById("inputId").value;
if(inputVal){
document.getElementById("result").innerHTML="<span style='color:green'>The value is "+inputVal+'</span>';
}
else{
document.getElementById("result").innerHTML="<span style='color:red'>Something error happen! the input May be empty.</span>";
}
}
<input type="text" id="inputId">
<input type="button" onclick="myFun()" value="View Result">
<h1 id="result"></h1>
当我们编写 empty 时,根据情况,它实质上可以表示以下任何一种;
在实际情况中,正如 OP 所述,我们可能希望测试它们所有,或者有时我们只想测试有限的条件集。
通常情况下,if(!a){return true;}
大多数时候都能够达到目的,但它并不能涵盖更广泛的条件。
另一个被广泛使用的 hack 是 return (!value || value == undefined || value == "" || value.length == 0);
但是,如果我们需要对整个过程进行控制呢?
在本机核心JavaScript中,没有简单的颈椎扭伤解决方案,必须进行采用。考虑到我们放弃对遗留IE11的支持(老实说,甚至Windows也已经这样了),以下解决方案源于挫败感,在所有现代浏览器中均可使用;
function empty (a,b=[])
{if(!Array.isArray(b)) return;
var conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)|| (typeof a === 'string' && conditions.includes(a.toString().trim())))
{return true;};
return false;};`
函数的第一次运行是检查b是否为数组,如果不是,则提前退出函数。
下一步是计算来自[null,'0','0.0',false,undefined,'']
和数组b的数组差异。如果b是空数组,则预定义条件将保持不变,否则它将删除匹配值。
条件= [预定义集]-[要排除的集]
filter函数正是这样做的。现在,我们只需检查值是否在条件数组中。 includes函数也是这样做,无需编写繁琐的循环,让JS引擎完成繁重的工作即可。注意 如果我们将a转换为字符串进行比较,那么0和0.0将运行良好,但Null和Undefined会抛出错误,阻止整个脚本。我们需要解决边缘情况。下面简单的||覆盖了边缘情况,如果第一个条件不满足,则会进行另一个早期检查以通过包含实现早期退出。
if(conditions.includes(a)|| (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim())))
trim() 函数将覆盖更宽的空格和制表符,仅处理值,并且只在边缘情况下发挥作用。
游乐场
function empty (a,b=[]){
if(!Array.isArray(b)) return;
conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)||
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
return true;
}
return false;
}
console.log('1 '+empty());
console.log('2 '+empty(''));
console.log('3 '+empty(' '));
console.log('4 '+empty(0));
console.log('5 '+empty('0'));
console.log('6 '+empty(0.0));
console.log('7 '+empty('0.0'));
console.log('8 '+empty(false));
console.log('9 '+empty(null));
console.log('10 '+empty(null,[null]));
console.log('11 dont check 0 as number '+empty(0,['0']));
console.log('12 dont check 0 as string '+empty('0',['0']));
console.log('13 as number for false as value'+empty(false,[false]));
function empty (a,b=[]){
if(!Array.isArray(b)) return;
conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(Array.isArray(a) && a.length > 0){
for (i = 0; i < a.length; i++) { if (empty(a[i],b))return true;}
}
if(conditions.includes(a)||
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
return true;
}
return false;
}
console.log('checking for all values '+empty([1,[0]]));
console.log('excluding for 0 from condition '+empty([1,[0]], ['0']));
这是我在框架中采用的简单且更广泛使用的功能;
if(data)
已经足够表达意思。 - CIsForCookiesundefined
是特殊情况之一,根据您的逻辑,应该触发// do something
,但实际上不会。 - Salman A