我如何检查一个变量,如果它是空或未定义,空和未定义之间的区别是什么? ==和===之间的区别是什么(很难搜索谷歌“===”)?


当前回答

广告1。Null不是全局对象属性的标识符,不像undefined可以

让x;/ /定义 让y =零;/ /空 让z = 3;//有值 // 'w' //未声明 If (!x) console.log('x为空或未定义'); 如果(!y) console.log('y是空的或未定义的'); If (!z) console.log('z为空或未定义'); Try {if(w) 0} catch(e) {console.log('w is undefined ')} // typeof不抛出未声明变量的异常 If (typeof w === 'undefined') console.log('w is undefined');

广告2。===检查值和类型。==不需要相同的类型,并在比较之前进行隐式转换(使用. valueof()和. tostring())。这里你有所有(src):

if

==(否定!=)

===(它的否定!==)

其他回答

广告1。Null不是全局对象属性的标识符,不像undefined可以

让x;/ /定义 让y =零;/ /空 让z = 3;//有值 // 'w' //未声明 If (!x) console.log('x为空或未定义'); 如果(!y) console.log('y是空的或未定义的'); If (!z) console.log('z为空或未定义'); Try {if(w) 0} catch(e) {console.log('w is undefined ')} // typeof不抛出未声明变量的异常 If (typeof w === 'undefined') console.log('w is undefined');

广告2。===检查值和类型。==不需要相同的类型,并在比较之前进行隐式转换(使用. valueof()和. tostring())。这里你有所有(src):

if

==(否定!=)

===(它的否定!==)

尝试不同的逻辑。你可以使用下面的代码检查所有(4)条件验证,如不null,不空白,不定义,不为零,只使用这个代码(!(!(变量)))在javascript和jquery。

function myFunction() {
var data;  //The Values can be like as null, blank, undefined, zero you can test

if(!(!(data)))
{
   //If data has valid value
    alert("data "+data);
} 
else 
{
    //If data has null, blank, undefined, zero etc.
    alert("data is "+data);
}

}

我如何检查一个变量,如果它是空的或未定义

检查一个变量是否有一个有效值,就像这样:

if(variable)

如果变量不包含:

零 未定义的 0 假 ""(空字符串) 南

如果你的(逻辑)检查是否定的(!),你想捕获JS的null和undefined(因为不同的浏览器会给你不同的结果),你会使用限制性较低的比较: 例如:

var ItemID = Item.get_id();
if (ItemID != null)
{
 //do stuff
}

这将捕获null和undefined

规范是这些问题的完整答案。以下是摘要:

For a variable x, you can: check whether it's null by direct comparison using ===. Example: x === null check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined". check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want. The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.

更多阅读:

安格斯·克罗尔的《真理、平等和JavaScript》 Andrea Giammarchi的JavaScript强制解密 JavaScript常见问题:JavaScript类型转换