jQuery检查是否为null / undefined / empty with!=不起作用

时间:2016-12-07 15:49:06

标签: javascript jquery logical-operators

我有这个jQuery代码

if (date != !date) {
    console.log(date);
}

date是一个数组,或null。如果它是一个数组,我想记录它,如果它是null我想在那里停止它。我认为!= !var正是出于此目的。当我尝试这个时,我也会得到null控制台日志。怎么样?

4 个答案:

答案 0 :(得分:2)

x始终不等于!x(这是x!= !x的意思)。

你想要的东西:x存在吗?它是空的吗?

if (date != null) {
    console.log(date);
}

var x1;
var x2 = [1,2];

if(x1 != null) // <- false
   console.log(x1); 

if(x2 != null) // <- true
  console.log(x2);

答案 1 :(得分:1)

试试这个,它应该抓住其他的一切......

if(Array.isArray(date)){
  console.log(date); 
}
else {
  console.log('not array');
}

答案 2 :(得分:-1)

试试这个:

if (date){
    console.log(date);
}

答案 3 :(得分:-2)

因此,您需要确定某个值是否为数组。这是ECMAScript标准推荐的另一种方法。有关此内容的更多信息,请参阅此帖子:Check if object is array?

&#13;
&#13;
var date = ['one', 'two', 'three'];
var txt = "bla ... bla ...";

if( Object.prototype.toString.call( date ) === '[object Array]' ) {
    console.log('is array');
} else {
    console.log(' not an array');
}

if( Object.prototype.toString.call( txt ) === '[object Array]' ) {
    console.log('is array');
} else {
    console.log('is not an array');
}
&#13;
&#13;
&#13;

相关问题