如何确定变量是否undefined或为null ? 我的代码如下:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
//DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
<div id="esd-names">
<div id="name"></div>
</div>
但是,如果执行此操作,JavaScript解释器将停止执行。
#1楼
结合以上答案,似乎最完整的答案是:
if( typeof variable === 'undefined' || variable === null ){
// Do stuff
}
这对于未声明或已声明并且显式设置为null或undefined的任何变量均适用。 对于任何具有实际非空值的已声明变量,布尔表达式的求值应为false。
#2楼
我只是有这个问题,即检查对象是否为空。 我只是用这个:
if (object) {
// Your code
}
例如:
if (document.getElementById("enterJob")) {
document.getElementById("enterJob").className += ' current';
}
#3楼
同时捕获null和undefined的标准方法是:
if (variable == null) {
// do something
}
-100%等同于更明确但不太简洁的代码:
if (variable === undefined || variable === null) {
// do something
}
在编写专业JS时, 类型相等和== vs ===的行为被理解是理所当然的。 因此,我们使用== ,仅与null比较。
重新编辑
暗示使用typeof的评论是完全错误的。 是的,如果变量不存在,上述解决方案将导致ReferenceError。 这是一件好事。 这个ReferenceError是可取的:它将帮助您发现错误并在发布代码之前解决它们,就像其他语言中的编译器错误一样。
您的代码中不应包含对未声明变量的任何引用。
#4楼
如果要检查的变量是全局变量,请执行
if (window.yourVarName) {
// Your code here
}
即使yourVarName变量不存在,这种检查方式也不会引发错误。
示例:我想知道我的浏览器是否支持History API
if (window.history) {
history.back();
}
工作原理:
window是一个对象,其中包含所有全局变量作为其属性,并且在JavaScript中尝试访问不存在的对象属性是合法的。 如果history不存在,则window.history返回undefined 。 undefined为false,因此if(undefined){}块中的代码将无法运行。
#5楼
调用typeof null返回值“ object”,因为特殊值null被认为是空对象引用。 版本5的Safari和版本7的Chrome都有一个怪癖,在正则表达式上调用typeof返回“功能”,而所有其他浏览器返回“对象”。
#6楼
由于您使用的是jQuery
var s; // undefined
jQuery.isEmptyObject(s); // will return true;
s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;
// usage
if(jQuery.isEmptyObject(s)){
alert('Either variable: s is undefined or its value is null');
}else{
alert('variable: s has value ' + s);
}
s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;
#7楼
您可以使用抽象相等运算符的品质来做到这一点:
if (variable == null){
// your code here.
}
因为null == undefined为true,所以上面的代码将捕获null和undefined 。
#8楼
jQuery attr()函数返回一个空字符串或实际值(并且永远不会为null或undefined )。 它唯一返回undefined时间是您的选择器未返回任何元素时。
因此,您可能要针对空白字符串进行测试。 另外,由于空白字符串,null和undefined为false-y,因此您可以执行以下操作:
if (!EmpName) { //do something }
#9楼
if (variable == null) {
// Do stuff, will only match null or undefined, this won't match false
}
#10楼
jQuery检查元素不为null
var dvElement = $('#dvElement');
if (dvElement.length > 0) {
//do something
}
else{
//else do something else
}
#11楼
if (typeof EmpName != 'undefined' && EmpName) {
如果值不是,则将评估为true:
- 空值
- 未定义
- N
- 空字符串(“”)
- 0
- 假
#12楼
var x;
if (x === undefined) {
alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("not even declared.")
};
您只能使用第二个:因为它将同时检查定义和声明
#13楼
我来为此编写自己的函数。 javascript很奇怪
几乎可用于任何东西。 (请注意,这还会检查变量是否包含任何可用的值 。但是由于通常也需要此信息,因此我认为值得发布)。 请考虑留下笔记。
function empty(v) {
let type = typeof v;
if (type === 'undefined') {
return true;
}
if (type === 'boolean') {
return !v;
}
if (v === null) {
return true;
}
if (v === undefined) {
return true;
}
if (v instanceof Array) {
if (v.length < 1) {
return true;
}
} else if (type === 'string') {
if (v.length < 1) {
return true;
}
if (v === '0') {
return true;
}
} else if (type === 'object') {
if (Object.keys(v).length < 1) {
return true;
}
} else if (type === 'number') {
if (v === 0) {
return true;
}
}
return false;
}
兼容打字稿。
编辑。 此函数应该做与PHP的empty()函数 完全相同的操作(请参见RETURN VALUES )
认为undefined , null , false , 0 , 0.0 , "0" {} []为空。
"0.0" , NaN , " " , true视为非空。
#14楼
要测试变量是否为null或未定义,请使用以下代码。
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}
#15楼
我在chrome控制台上运行此测试,使用(void 0)可以检查undefined
var c;
undefined
if(c === void 0)alert();
// output = undefined
var c = 1;
// output = undefined
if(c === void 0)alert();
// output = undefined
// check c value c
// output = 1
if(c === void 0)alert();
// output = undefined
c = undefined;
// output = undefined
if(c === void 0)alert();
// output = undefined
#16楼
最好的办法:
if(typeof variable==='undefined' || variable===null) {
/* do your stuff */
}
#17楼
var i;
if(i === null || typeof i === 'undefined'){
console.log(i,'i is undefined or null')
}else{
console.log(i,'i has some value')
}
#18楼
这是一个非常老的问题,但是我仍然认为测试这两个条件的最佳/安全方法是将值转换为字符串:
var EmpName = $("div#esd-names div#name").attr('class');
// Undefined check
if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
// do something with your code
}
// Nullcheck
if (Object.prototype.toString.call(EmpName) === '[object Null]'){
// do something with your code
}
#19楼
您可以使用typeof来检查该值是未定义还是为null:
if(typeof value == 'undefined'){
#20楼
if(x==null)在javascript中是个坏主意,用"=="判断可能会导致意外的类型强制,并且不能由coffee-script读取, 在条件判断中切勿使用“ ==”或“!=” !
if(x)会更好。但是请小心0和“” ,将其视为false ,否则不等于"!= null"为true 。
https://www.w3schools.com/js/js_best_practices.asp
#21楼
使用以下解决方案:
const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);
console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...
我可以检查以下内容:
- 空值
- 未定义
- N
- 空的
- 字串(“”)
- 0
- 假
#22楼
(null == undefined) // true
(null === undefined) // false
因为===同时检查类型和值。 两者的类型不同,但值相同。
#23楼
最简单的检查方法是:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
#24楼
您可以简单地使用以下代码(我知道这样做的方法更短,但这可以使视觉上更容易观察,而其他查看代码的人则至少可以这样做)。
if (x === null || x === undefined) {
// add your response code here etc.
}
#25楼
最短和最容易的:
if(!EmpName ){
// DO SOMETHING
}
如果EmpName为:
- 空值
- 未定义
- N
- 空的
- 字串(“”)
- 0
- 假
#26楼
据我所知,在Javascript中,我们可以像下面这样检查undefined,null或empty var。
if (var === undefined){
}
if (var === null){
}
if (var === ''){
}
检查所有状况
if(var === undefined || var === null || var === ''){
}