Ale*_*lex 2088 javascript null undefined
是否有一个通用的JavaScript函数来检查变量是否有值并确保它不是undefined
或null
?我有这个代码,但我不确定它是否涵盖了所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
Run Code Online (Sandbox Code Playgroud)
jAn*_*ndy 4097
您可以检查变量是否具有truthy
值.这意味着
if( value ) {
}
Run Code Online (Sandbox Code Playgroud)
将计算为true
,如果value
是不是:
以上列表表示falsy
ECMA-/Javascript中的所有可能值.在该部分的规范中找到它ToBoolean
.
此外,如果您不知道变量是否存在(即,如果已声明),则应与typeof
运营商核实.例如
if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
Run Code Online (Sandbox Code Playgroud)
如果可以确定至少声明了变量,则应直接检查它是否具有truthy
如上所示的值.
进一步阅读:http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html
Sal*_*n A 204
检查值是未定义还是null的详细方法是:
return value === undefined || value === null;
Run Code Online (Sandbox Code Playgroud)
您也可以使用==
运算符,但这需要人们知道所有规则:
return value == null; // also returns true if value is undefined
Run Code Online (Sandbox Code Playgroud)
Mik*_*uel 73
function isEmpty(value){
return (value == null || value.length === 0);
}
Run Code Online (Sandbox Code Playgroud)
这将返回true
undefined // Because undefined == null
null
[]
""
Run Code Online (Sandbox Code Playgroud)
和零参数函数,因为函数length
是它所采用的声明参数的数量.
要禁止后一类,您可能只想检查空字符串
function isEmpty(value){
return (value == null || value === '');
}
Run Code Online (Sandbox Code Playgroud)
guy*_*uya 35
我知道这是一个老问题,但这是最安全的检查,我没有看到它在这里发布完全相同:
if (typeof value != 'undefined' && value) {
//deal with value'
};
Run Code Online (Sandbox Code Playgroud)
它将涵盖从未定义过价值的案例,以及以下任何一个案例:
PS不需要类型值严格相等!='undefined'
Vix*_*Vix 27
您可能会发现以下功能有用:
function typeOf(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
Run Code Online (Sandbox Code Playgroud)
或者在ES7中(如果进一步改进则发表评论)
function typeOf(obj) {
const { toString } = Object.prototype;
const stringified = obj::toString();
const type = stringified.split(' ')[1].slice(0, -1);
return type.toLowerCase();
}
Run Code Online (Sandbox Code Playgroud)
结果:
typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map
Run Code Online (Sandbox Code Playgroud)
"请注意,绑定运算符(::)不是ES2016(ES7)的一部分,也不是ECMAScript标准的任何后续版本.它目前是引入该语言的第0阶段(草编)提议." - 西蒙凯尔伯格 作者希望加入他对这一美丽提案的支持,以获得皇室提升.
小智 25
评分最高的第一个答案是错误的.如果value未定义,它将在现代浏览器中引发异常.你必须使用:
if (typeof(value) !== "undefined" && value)
Run Code Online (Sandbox Code Playgroud)
要么
if (typeof value !== "undefined" && value)
Run Code Online (Sandbox Code Playgroud)
Dan*_*iaz 17
看看新的 ECMAScript Nullish 合并运算符
您可以将此功能(??
运算符)视为在处理null
或时“回退”到默认值的一种方式undefined
。
let x = foo ?? bar();
Run Code Online (Sandbox Code Playgroud)
同样,上面的代码等价于下面的代码。
let x = (foo !== null && foo !== undefined) ? foo : bar();
Run Code Online (Sandbox Code Playgroud)
Ari*_*rif 16
!检查空字符串(""),null,undefined,false以及数字0和NaN.比如,如果字符串为空var name = ""
则console.log(!name)
返回true
.
function isEmpty(val){
return !val;
}
Run Code Online (Sandbox Code Playgroud)
如果val为空,null,undefined,false,数字0或NaN,则此函数将返回true .
tco*_*ooc 13
你有点过头了.要检查变量是否未赋值,您只需要检查undefined和null.
function isEmpty(value){
return (typeof value === "undefined" || value === null);
}
Run Code Online (Sandbox Code Playgroud)
这是假设0
,""
和对象(甚至空对象和数组)是有效的"值".
小智 13
这种情况检查
if (!!foo) {
//foo is defined
}
Run Code Online (Sandbox Code Playgroud)
是你所需要的全部.
Ale*_*gro 12
我非常喜欢的解决方案:
让我们定义一个空白变量是null
或undefined
,或者如果它的长度是零,或者是一个对象,则没有键:
function isEmpty (value) {
return (
// null or undefined
(value == null) ||
// has length and it's zero
(value.hasOwnProperty('length') && value.length === 0) ||
// is an Object and has no keys
(value.constructor === Object && Object.keys(value).length === 0)
)
}
Run Code Online (Sandbox Code Playgroud)
返回值:
undefined
,null
,""
,[]
,{}
true
,false
,1
,0
,-1
,"foo"
,[1, 2, 3]
,{ foo: 1 }
l3x*_*l3x 11
如果你更喜欢普通的javascript试试这个:
/**
* Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
* length of `0` and objects with no own enumerable properties are considered
* "empty".
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if the `value` is empty, else `false`.
* @example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty([]);
* // => true
*
* _.isEmpty({});
* // => true
*
* _.isEmpty('');
* // => true
*/
function isEmpty(value) {
if (!value) {
return true;
}
if (isArray(value) || isString(value)) {
return !value.length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
否则,如果您已经使用下划线或lodash,请尝试:
_.isEmpty(value)
Run Code Online (Sandbox Code Playgroud)
这是我的 - 如果value为null,undefined等等或空白(即仅包含空格),则返回true:
function stringIsEmpty(value) {
return value ? value.trim().length == 0 : true;
}
Run Code Online (Sandbox Code Playgroud)
我不建议尝试定义或使用一个函数来计算整个世界中是否有任何值是空的。“空”的真正含义是什么?如果有let human = { name: 'bob', stomach: 'empty' }
,应该isEmpty(human)
退true
吗?如果有let reg = new RegExp('');
,应该isEmpty(reg)
退true
吗?怎么样isEmpty([ null, null, null, null ])
- 这个列表只包含空,那么列表本身是空的?我想在这里提出一些关于 javascript 中“空洞性”(一个故意模糊的词,以避免预先存在的关联)的注释——我想争辩说,javascript 值中的“空洞性”永远不应该被笼统地处理。
为了决定如何确定值的“空性”,我们需要适应 javascript 内在的、对值是“真”还是“假”的固有感觉。自然,null
并且undefined
都是“假的”。不太自然的是,这个数字0
(除了 没有其他数字NaN
)也是“假的”。最不自然的是:''
是假的,但是[]
and {}
(and new Set()
, and new Map()
) 是真的——尽管它们看起来都同样空洞!
还有一些关于null
vs 的讨论undefined
——我们真的需要两者来表达我们程序中的空性吗?我个人避免让字母 u、n、d、e、f、i、n、e、d 以该顺序出现在我的代码中。我总是null
用来表示“空虚”。不过,我们再次需要适应 javascript 对如何null
和undefined
不同的固有感觉:
undefined
undefined
:let f = a => a;
console.log(f('hi'));
console.log(f());
Run Code Online (Sandbox Code Playgroud)
undefined
,而不是null
:let f = (v='hello') => v;
console.log(f(null));
console.log(f(undefined));
Run Code Online (Sandbox Code Playgroud)
对我来说,null
是空虚的明确能指;“本来可以填写的东西被故意留空了”。
确实undefined
是一种必要的复杂性,允许一些 js 功能存在,但在我看来,它应该始终留在幕后;没有直接接触。undefined
例如,我们可以将其视为实现默认函数参数的 javascript 机制。如果您不向函数提供参数,它将收到一个值undefined
。如果该参数最初设置为 ,则默认值将应用于函数参数undefined
。在这种情况下undefined
是默认函数参数的关键,但它留在后台:我们可以实现默认参数功能,而无需参考undefined
:
这是默认参数的错误实现,因为它直接与undefined
:
let fnWithDefaults = arg => {
if (arg === undefined) arg = 'default';
...
};
Run Code Online (Sandbox Code Playgroud)
这是一个很好的实现:
let fnWithDefaults = (arg='default') => { ... };
Run Code Online (Sandbox Code Playgroud)
这是接受默认参数的一种糟糕方式:
fnWithDefaults(undefined);
Run Code Online (Sandbox Code Playgroud)
只需这样做:
fnWithDefaults();
Run Code Online (Sandbox Code Playgroud)
我认为永远不应该以通用的方式处理空洞。相反,在确定数据是否为空之前,我们应该始终严格获取有关我们数据的更多信息 - 我主要通过检查我正在处理的数据类型来做到这一点:
let fnWithDefaults = arg => {
if (arg === undefined) arg = 'default';
...
};
Run Code Online (Sandbox Code Playgroud)
请注意,此函数忽略多态性 - 它期望value
是 的直接实例Cls
,而不是 的子类的实例Cls
。我避免instanceof
的主要原因有两个:
([] instanceof Object) === true
(“数组是一个对象”)('' instanceof String) === false
(“字符串不是字符串”)需要注意的是Object.getPrototypeOf
用来避免这样的情况下,let v = { constructor: String };
该isType
功能仍正常返回isType(v, String)
(假),和isType(v, Object)
(真正的)。
总的来说,我建议使用此isType
功能以及以下提示:
let v = JSON.parse(someRawValue);
,我们的v
变量现在是未知类型。我们应该尽早限制我们的可能性。执行此操作的最佳方法可能是要求特定类型:例如if (!isType(v, Array)) throw new Error('Expected Array');
- 这是一种非常快速且富有表现力的方法,可以去除 的泛型性质v
,并确保它始终是Array
. 但是,有时我们需要允许v
具有多种类型。在这些情况下,我们应该尽早创建v
不再通用的代码块:let fnWithDefaults = (arg='default') => { ... };
Run Code Online (Sandbox Code Playgroud)
if (v === null) throw new Error('Null value rejected');
- 这对于确保null
值不会通过,但如果值确实通过,我们仍然几乎不知道关于它的任何事情。值v
其通过这个空检查仍然是非常通用的-它的任何东西,但null
!黑名单很难消除通用性。null
,否则永远不要考虑“空值”。相反,请考虑“一个空的 X”。本质上,永远不要考虑做任何类似的事情if (isEmpty(val)) { /* ... */ }
——不管这个isEmpty
功能是如何实现的(我不想知道......),它没有意义!而且太笼统了!真空度只能在了解val
的类型的情况下计算。真空度检查应如下所示:
“一个字符串,没有字符”:
if (isType(val, String) && val.length === 0) ...
“一个对象,有 0 个道具”: if (isType(val, Object) && Object.entries(val).length === 0) ...
“一个数字,等于或小于零”: if (isType(val, Number) && val <= 0) ...
“一个数组,没有项目”: if (isType(val, Array) && val.length === 0) ...
唯一的例外是 whennull
用于表示某些功能。在这种情况下,说“一个空值”是有意义的:if (val === null) ...
您可以使用空合并运算符??
来检查null
和undefined
值。请参阅MDN 文档
null ?? 'default string'; // returns "default string"
0 ?? 42; // returns 0
(null || undefined) ?? "foo"; // returns "foo"
Run Code Online (Sandbox Code Playgroud)
如果尚未声明该变量,则将无法使用函数测试未定义变量,因为会出现错误。
if (foo) {}
function (bar) {}(foo)
Run Code Online (Sandbox Code Playgroud)
如果尚未声明foo,则两者都会产生错误。
如果要测试是否已声明变量,可以使用
typeof foo != "undefined"
Run Code Online (Sandbox Code Playgroud)
如果要测试是否已声明foo并且它具有一个值,则可以使用
if (typeof foo != "undefined" && foo) {
//code here
}
Run Code Online (Sandbox Code Playgroud)
检查默认值
function typeOfVar (obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
function isVariableHaveDefaltVal(variable) {
if ( typeof(variable) === 'string' ) { // number, boolean, string, object
console.log(' Any data Between single/double Quotes is treated as String ');
return (variable.trim().length === 0) ? true : false;
}else if ( typeof(variable) === 'boolean' ) {
console.log('boolean value with default value \'false\'');
return (variable === false) ? true : false;
}else if ( typeof(variable) === 'undefined' ) {
console.log('EX: var a; variable is created, but has the default value of undefined.');
return true;
}else if ( typeof(variable) === 'number' ) {
console.log('number : '+variable);
return (variable === 0 ) ? true : false;
}else if ( typeof(variable) === 'object' ) {
// -----Object-----
if (typeOfVar(variable) === 'array' && variable.length === 0) {
console.log('\t Object Array with length = ' + [].length); // Object.keys(variable)
return true;
}else if (typeOfVar(variable) === 'string' && variable.length === 0 ) {
console.log('\t Object String with length = ' + variable.length);
return true;
}else if (typeOfVar(variable) === 'boolean' ) {
console.log('\t Object Boolean = ' + variable);
return (variable === false) ? true : false;
}else if (typeOfVar(variable) === 'number' ) {
console.log('\t Object Number = ' + variable);
return (variable === 0 ) ? true : false;
}else if (typeOfVar(variable) === 'regexp' && variable.source.trim().length === 0 ) {
console.log('\t Object Regular Expression : ');
return true;
}else if (variable === null) {
console.log('\t Object null value');
return true;
}
}
return false;
}
var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");
//The "g" flag in the regex will cause all spaces to get replaced.
Run Code Online (Sandbox Code Playgroud)
检查结果:
isVariableHaveDefaltVal(' '); // string
isVariableHaveDefaltVal(false); // boolean
var a;
isVariableHaveDefaltVal(a);
isVariableHaveDefaltVal(0); // number
isVariableHaveDefaltVal(parseInt('')); // NAN isNAN(' '); - true
isVariableHaveDefaltVal(null);
isVariableHaveDefaltVal([]);
isVariableHaveDefaltVal(/ /);
isVariableHaveDefaltVal(new Object(''));
isVariableHaveDefaltVal(new Object(false));
isVariableHaveDefaltVal(new Object(0));
typeOfVar( function() {} );
Run Code Online (Sandbox Code Playgroud)
我使用@Vix函数()来检查哪种类型的对象.
使用instansof«
var prototypes_or_Literals = function (obj) {
switch (typeof(obj)) {
// object prototypes
case 'object':
if (obj instanceof Array)
return '[object Array]';
else if (obj instanceof Date)
return '[object Date]';
else if (obj instanceof RegExp)
return '[object regexp]';
else if (obj instanceof String)
return '[object String]';
else if (obj instanceof Number)
return '[object Number]';
else
return 'object';
// object literals
default:
return typeof(obj);
}
};
output test «
prototypes_or_Literals( '' ) // "string"
prototypes_or_Literals( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]"
Run Code Online (Sandbox Code Playgroud)
这可能是有用的。
数组中的所有值都表示您想要的内容(空,未定义或其他内容),然后在其中搜索所需内容。
var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1
Run Code Online (Sandbox Code Playgroud)
尝试不同的逻辑。您可以使用下面的代码检查所有四(4)条件进行验证,例如非空,非空白,非未定义和非零仅在javascript和jquery中使用此代码(!(!(变量)))。
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}
Run Code Online (Sandbox Code Playgroud)
function isEmpty(obj) {
if (typeof obj == 'number') return false;
else if (typeof obj == 'string') return obj.length == 0;
else if (Array.isArray(obj)) return obj.length == 0;
else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
else if (typeof obj == 'boolean') return false;
else return !obj;
}
Run Code Online (Sandbox Code Playgroud)
在带有修剪以处理空白字符串的ES6中:
const isEmpty = value => {
if (typeof value === 'number') return false
else if (typeof value === 'string') return value.trim().length === 0
else if (Array.isArray(value)) return value.length === 0
else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
else if (typeof value === 'boolean') return false
else return !value
}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用TypeScript
并且不想考虑“这些值false
”,那么这就是您的解决方案:
第一的: import { isNullOrUndefined } from 'util';
然后: isNullOrUndefined(this.yourVariableName)
请注意:如下所述,现在已弃用此选项,请改用value === undefined || value === null
。参考号
return val || 'Handle empty variable'
Run Code Online (Sandbox Code Playgroud)
是在很多地方处理它的一种非常不错的方法,也可以用于分配变量
const res = val || 'default value'
Run Code Online (Sandbox Code Playgroud)
根据jAndy 的回答,如果您想避免值为以下任一值时为 true :
可能避免获得真值的一种可能的解决方案如下:
function isUsable(valueToCheck) {
if (valueToCheck === 0 || // Avoid returning false if the value is 0.
valueToCheck === '' || // Avoid returning false if the value is an empty string.
valueToCheck === false || // Avoid returning false if the value is false.
valueToCheck) // Returns true if it isn't null, undefined, or NaN.
{
return true;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
其使用方式如下:
if (isUsable(x)) {
// It is usable!
}
// Make sure to avoid placing the logical NOT operator before the parameter (isUsable(!x)) and instead, use it before the function, to check the returned value.
if (!isUsable(x)) {
// It is NOT usable!
}
Run Code Online (Sandbox Code Playgroud)
除了这些情况之外,如果对象或数组为空,您可能希望返回 false:
你可以这样处理:
function isEmptyObject(valueToCheck) {
if(typeof valueToCheck === 'object' && !Object.keys(valueToCheck).length){
// Object is empty!
return true;
} else {
// Object is not empty!
return false;
}
}
function isEmptyArray(valueToCheck) {
if(Array.isArray(valueToCheck) && !valueToCheck.length) {
// Array is empty!
return true;
} else {
// Array is not empty!
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想检查所有空白字符串(“”),您可以执行以下操作:
function isAllWhitespace(){
if (valueToCheck.match(/^ *$/) !== null) {
// Is all whitespaces!
return true;
} else {
// Is not all whitespaces!
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
注意: hasOwnProperty
如果变量被声明为空字符串、0、false、NaN、null 和 undefined,则返回 true,因此它可能不是最好的使用方式。可以修改该函数以使用它来显示它已声明,但不可用。
可能最短的答案是
val==null || val==''
Run Code Online (Sandbox Code Playgroud)
如果将右侧更改为val===''
空数组,则为false。证明
val==null || val==''
Run Code Online (Sandbox Code Playgroud)
有关==
(来源在这里)的更多详细信息
奖励:原因===
比==
要编写清晰易懂的代码,请使用明确的接受值列表
val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)
Run Code Online (Sandbox Code Playgroud)
function isEmpty(val){
return val==null || val==''
}
// ------------
// TEST
// ------------
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);
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" - so we should get here TRUE
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1627984 次 |
最近记录: |