提问人:sadmicrowave 提问时间:4/16/2010 最后编辑:Dave Mackeysadmicrowave 更新时间:8/31/2023 访问量:3396669
如何确定变量是“undefined”还是“null”?
How can I determine if a variable is 'undefined' or 'null'?
问:
如何确定变量是否为 或?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>
但是当我这样做时,JavaScript 解释器会停止执行。
答:
您可以使用抽象相等运算符的特性来执行此操作:
if (variable == null){
// your code here.
}
因为是真的,所以上面的代码将同时捕获 和 。null == undefined
null
undefined
评论
const y = undefined; y == null;
true
y
abc
y
y
console.log(y == null);
true
=
==
const
undefined !== null
undefined == null
jQuery 函数返回空白字符串或实际值(从不返回 或 )。它唯一返回的时间是选择器未返回任何元素时。attr()
null
undefined
undefined
因此,您可能希望针对空白字符串进行测试。或者,由于空白字符串、null 和 undefined 是 false-y,因此您可以这样做:
if (!EmpName) { //do something }
评论
ReferenceError: EmpName is not defined
undefined
img
src
undefined
$('img').attr('src');
if (variable == null) {
// Do stuff, will only match null or undefined, this won't match false
}
评论
undefined
null
/*jshint eqnull:true */
== null
==
if(variable == null)
结合以上答案,似乎最完整的答案是:
if( typeof variable === 'undefined' || variable === null ){
// Do stuff
}
这应该适用于任何未声明或已声明并显式设置为 null 或未定义的变量。对于具有实际非 null 值的任何声明变量,布尔表达式的计算结果应为 false。
评论
typeof
variable == null
我刚刚遇到了这个问题,即检查一个对象是否为空。
我只是使用它:
if (object) {
// Your code
}
例如:
if (document.getElementById("enterJob")) {
document.getElementById("enterJob").className += ' current';
}
评论
同时捕捉和捕获的标准方法是:null
undefined
if (variable == null) {
// do something
}
--这 100% 等同于更明确但不太简洁的:
if (variable === undefined || variable === null) {
// do something
}
在编写专业 JS 时,人们理所当然地认为类型相等和 ==
与 ===
的行为是可以理解的。因此,我们使用 并且仅与 进行比较。==
null
再次编辑
建议使用的评论是完全错误的。是的,如果变量不存在,我上面的解决方案将导致 ReferenceError。这是一件好事。这个 ReferenceError 是可取的:它将帮助您在交付代码之前找到错误并修复它们,就像其他语言中的编译器错误一样。如果您正在处理您无法控制的输入,请使用 /。typeof
try
catch
代码中不应有任何对未声明变量的引用。
评论
undefined
var someVar;
if (variable)
false
0
NaN
null
undefined
instanceof
null
undefined
instanceof
如果要检查的变量是全局变量,请执行
if (window.yourVarName) {
// Your code here
}
即使变量不存在,这种检查方式也不会抛出错误。yourVarName
示例:我想知道我的浏览器是否支持历史记录 API
if (window.history) {
history.back();
}
工作原理:
window
是一个包含所有全局变量作为其属性的对象,在 JavaScript 中,尝试访问不存在的对象属性是合法的。如果不存在,则返回 。 是 falsey,因此块中的代码不会运行。history
window.history
undefined
undefined
if(undefined){}
评论
null
undefined
0
false
''
undefined
null
调用 typeof null 返回值“object”,因为特殊值 null 被视为空对象引用。Safari 版本 5 和 Chrome 版本 7 有一个怪癖,即在正则表达式上调用 typeof 返回“function”,而所有其他浏览器返回“object”。
由于您使用的是 jQuery,因此可以使用单个函数来确定变量是未定义还是其值为 null。
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;
评论
ReferenceError: s is not defined
jQuery 检查元素不为空:
var dvElement = $('#dvElement');
if (dvElement.length > 0) {
// Do something
}
else{
// Else do something else
}
if (typeof EmpName != 'undefined' && EmpName) {
如果 value 不是,则计算结果为 true:
零
定义
南
空字符串 (“”)
0
假
评论
if (EmpName)
undefined
var EmpName; if (EmpName)
var x;
if (x === undefined) {
alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("not even declared.")
};
您只能使用第二个:因为它将检查定义和声明
编辑后的答案:在我看来,你不应该使用我下面的旧答案中的函数。相反,你可能应该知道变量的类型,并直接使用“根据”检查(例如,想知道数组是否为空?只是做等)。这个答案甚至没有回答OP的问题。if(arr.length===0){}
我来为此编写自己的函数。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;
}
TypeScript 兼容。
这个函数应该像 PHP 的 empty()
函数一样做同样的事情(参见RETURN VALUES
)
将 、 、 、 、 视为空。undefined
null
false
0
0.0
"0"
{}
[]
"0.0"
、、、 被视为非空。NaN
" "
true
评论
{ }
Object.keys( obj ).length < 1
==
===
为了测试变量是否为 null 或未定义,我使用以下代码。
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}
评论
typeof
undefined
我在 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
最佳方法:
if(typeof variable==='undefined' || variable===null) {
/* do your stuff */
}
评论
var i;
if (i === null || typeof i === 'undefined') {
console.log(i, 'i is undefined or null')
}
else {
console.log(i, 'i has some value')
}
评论
typeof
undefined
'undefined'
i == null
i
undefined
我仍然认为测试这两个条件的最佳/安全方法是将值转换为字符串:
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
}
评论
只需使用 typeof 即可检查值是否为 undefined 或 null:
if(typeof value == 'undefined'){
评论
null
使用以下解决方案:
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...
我能够检查以下内容:
- 零
- 定义
- 南
- 空
- 字符串 (“”)
- 0
- 假
评论
(null == undefined) // true
(null === undefined) // false
因为 === 同时检查类型和值。两者的类型不同,但值相同。
最简单的检查方法是:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
评论
false
undefined
null
NaN
false
!
variable
您可以简单地使用以下方法(我知道有更短的方法可以做到这一点,但这可能会使视觉观察更容易,至少对于查看代码的其他人来说是这样)。
if (x === null || x === undefined) {
// Add your response code here, etc.
}
来源: https://www.growthsnippets.com/how-can-i-determine-if-a-variable-is-undefined-or-null/
最短和最简单的:
if(!EmpName ){
// DO SOMETHING
}
如果 EmpName 为以下情况,这将计算为 true:
- 零
- 定义
- 南
- 空
- 字符串 (“”)
- 0
- 假
评论
在 JavaScript 中,据我所知,我们可以检查一个未定义的、null 或空的变量,如下所示。
if (variable === undefined){
}
if (variable === null){
}
if (variable === ''){
}
检查所有条件:
if(variable === undefined || variable === null || variable === ''){
}
评论
var
是一个保留词,这会抛出SyntaxError
可能最短的方法是:
if(EmpName == null) { /* DO SOMETHING */ };
这是证据:
function check(EmpName) {
if(EmpName == null) { return true; };
return false;
}
var log = (t,a) => console.log(`${t} -> ${check(a)}`);
log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");
// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined"
以下是有关(来源在这里==
)
奖励:原因比(看agc答案)更清楚===
==
)
评论
if(var)/if(!var)
true/false
if(var == null)
让我们看看这个,
let apple; // Only declare the variable as apple alert(apple); // undefined
在上面,变量仅声明为 .在这种情况下,如果我们调用 method,它将显示 undefined。
apple
alert
let apple = null; /* Declare the variable as apple and initialized but the value is null */ alert(apple); // null
在第二个中,它显示 null,因为 value 的变量为 null。apple
因此,您可以检查值是 undefined 还是 null。
if(apple !== undefined || apple !== null) {
// Can use variable without any error
}
检查应该可以解决问题,并以最短的方式解决“未定义或空”的情况。(不考虑“foo 未申报”的情况。但是习惯于 3 等号(作为最佳实践)的人可能不会接受它。看看 eslint 和 tslint 中的 eqeqeq 或三等规则......foo == null
在这种情况下,当我们检查变量是变量还是单独变量时,应该应用显式方法,我对这个主题的贡献(现在是 27 个非否定答案!)是用作执行检查的简短而安全的方法。undefined
null
void 0
undefined
使用是不安全的,因为 undefined 不是保留字,可以被遮蔽 (MDN)。使用 check 是安全的,但是如果我们不关心 foo-is-undeclared 的情况,可以使用以下方法:foo === undefined
typeof === 'undefined'
if (foo === void 0 || foo === null) { ... }
如果创建一个函数来检查它:
export function isEmpty (v) {
if (typeof v === "undefined") {
return true;
}
if (v === null) {
return true;
}
if (typeof v === "object" && Object.keys(v).length === 0) {
return true;
}
if (Array.isArray(v) && v.length === 0) {
return true;
}
if (typeof v === "string" && v.trim().length === 0) {
return true;
}
return false;
}
最简单的答案:
if(!EmpName){
// DO SOMETHING
};
评论
0
''
nullish
undefined
使用最新的 javascript 更改,您可以使用新的逻辑运算符来检查左操作数是否为 或 如果是,则分配右操作数的值。??=
null
undefined
所以
if(EmpName == null){ // if Variable EmpName null or undefined
EmpName = 'some value';
};
相当于:
EmpName ??= 'some value';
你可以做这样的事情,我认为在一个条件下对同一变量进行多值检查更有效
const x = undefined;
const y = null;
const z = 'test';
if ([undefined, null].includes(x)) {
// Will return true
}
if ([undefined, null].includes(y)) {
// Will return true
}
if ([undefined, null].includes(z)) {
// Will return false
}
似乎还没有人发布这个,所以我们开始吧:
a?.valueOf() === undefined
可靠地适用于任一或 。null
undefined
以下作品与 OR 非常相似,但对于不喜欢😎的纯粹主义者来说可能更具吸引力a == null
a == undefined
==
function check(a) {
const value = a?.valueOf();
if (value === undefined) {
console.log("a is null or undefined");
}
else {
console.log(value);
}
}
check(null);
check(undefined);
check(0);
check("");
check({});
check([]);
顺便说一句,也有效:a?.constructor
function check(a) {
if (a?.constructor === undefined) {
console.log("a is null or undefined");
}
}
check(null);
check(undefined);
check(0);
check("");
check({});
check([]);
更新:我们与 StackOverflow 成员一起制定了更好的方法。
我个人会这样做:
if (Object.is(a ?? null, null)) {
// a is null or undefined
}
评论
一个?.valueOf() === undefined
可靠地工作“....石明a = {valueOf() {}}
a = Object.create(null)
如果您想坚持使用运算符并澄清代码,您也可以这样做。(value ?? null) === null
===
所以,到目前为止,有三种方式。
value == null
value === null || value === undefined
(value ?? null) === null
我通常会避免,但这一次,我更喜欢.==
== null
评论
Symbol()
(a ?? null) === null
(a ?? undefined) === undefined
评论