提问人:Alex 提问时间:4/1/2011 最后编辑:Alex 更新时间:5/31/2023 访问量:2909534
是否有标准函数来检查 JavaScript 中的空变量、未定义变量或空白变量?[复制]
Is there a standard function to check for null, undefined, or blank variables in JavaScript? [duplicate]
问:
是否有通用的 JavaScript 函数来检查变量是否具有值并确保它不是 or ?我有这个代码,但我不确定它是否涵盖所有情况:undefined
null
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
答:
您可以检查变量是否有值。这意味着truthy
if (value) {
// do something..
}
将评估为,如果不是:true
value
- 零
- 定义
- 南
- 空字符串 (“”)
- 0
- 假
上面的列表表示 ECMA-/Javascript 中所有可能的值。在该部分的规范中找到它。falsy
ToBoolean
此外,如果您不知道某个变量是否存在(这意味着,如果它已声明),则应与运算符联系。例如typeof
if (typeof foo !== 'undefined') {
// foo could get resolved and it's defined
}
如果可以确定至少声明了一个变量,则应直接检查它是否具有如上所示的值。truthy
评论
if( value || value === false )
truthy
value.length != 0
if
var result = undefined ? "truthy" : "falsy"
!!
!!1 // true
!!null // false
function isEmpty(value){
return (value == null || value.length === 0);
}
这将返回 true
undefined // Because undefined == null
null
[]
""
和零参数函数,因为函数的参数是它所采用的声明参数的数量。length
若要禁止后一类,可能只想检查空白字符串
function isEmpty(value){
return (value == null || value === '');
}
空格或空格
function isEmpty(value){
return (value == null || value.trim().length === 0);
}
评论
undefined == null
但undefined !== null
检查值是否为 undefined 或 null 的详细方法是:
return value === undefined || value === null;
您也可以使用运算符,但这需要了解所有规则:==
return value == null; // also returns true if value is undefined
评论
null
undefined
if (value == null)
==
if (value === null || value === undefined)
arg == null
arg === undefined || arg === null
arg == null
在我的经验中很常见。
return value === (void 0)
可悲的是,它比测试更安全,测试很可能是范围上的合法变量。undefined
你有点过头了。要检查变量是否未被赋予值,您只需要检查 undefined 和 null。
function isEmpty(value){
return (typeof value === "undefined" || value === null);
}
这是假设 、 和 对象(甚至是空对象和数组)是有效的“值”。0
""
评论
null
let isEmpty = val => val == null;
如果尚未声明变量,则无法使用函数测试未定义,因为将出现错误。
if (foo) {}
function (bar) {}(foo)
如果尚未声明 foo,两者都将生成错误。
如果要测试是否已声明变量,可以使用
typeof foo != "undefined"
如果要测试是否已声明 Foo,并且它具有可以使用的值
if (typeof foo != "undefined" && foo) {
//code here
}
这是最安全的检查,我还没有看到它完全像这样张贴在这里:
if (typeof value !== 'undefined' && value) {
//deal with value'
};
它将涵盖从未定义过值的情况,以及以下任何一种情况:
- 零
- undefined(undefined 的值与从未定义的参数不同)
- 0
- “”(空字符串)
- 假
- 南
编辑:更改为严格平等 (!==),因为它现在是常态 ;)
评论
typeof
val !== null
这是我的 - 如果 value 为 null、undefined 等或空白(即仅包含空格),则返回 true:
function stringIsEmpty(value) {
return value ? value.trim().length == 0 : true;
}
评论
第一个评分最高的答案是错误的。如果 value 未定义,它将在现代浏览器中引发异常。您必须使用:
if (typeof(value) !== "undefined" && value)
或
if (typeof value !== "undefined" && value)
评论
undefined
if(value === 0) gameOver();
;)
value
!检查空字符串 (“”)、null、undefined、false 以及数字 0 和 NaN。比如说,如果一个字符串是空的,则返回 .var name = ""
console.log(!name)
true
function isEmpty(val){
return !val;
}
如果 val 为空、null、undefined、false、数字 0 或 NaN,则此函数将返回 true。
或
根据您的问题域,您可以只使用 like 或 .!val
!!val
评论
isEmpty(val)
!val
!val
!!val
您可能会发现以下函数很有用:
function typeOf(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
或者在 ES7 中(如果进一步改进,请发表评论)
function typeOf(obj) {
const { toString } = Object.prototype;
const stringified = obj::toString();
const type = stringified.split(' ')[1].slice(0, -1);
return type.toLowerCase();
}
结果:
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
“请注意,绑定运算符 (::) 不是 ES2016 (ES7) 的一部分,也不是 ECMAScript 标准的任何更高版本的一部分。目前,它被引入该语言的阶段 0(稻草人)提案。作者希望对这个美丽的提议表示支持,以接受皇家升天。
评论
::
此条件检查
if (!!foo) {
//foo is defined
}
就是你所需要的。
评论
if
if(foo)
active={!!foo}
如果您更喜欢纯 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;
}
否则,如果您已经在使用下划线或 lodash,请尝试:
_.isEmpty(value)
评论
isArray
isString
window
检查默认值
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.
检查结果:
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() {} );
我使用 @Vix function() 来检查哪种类型的对象。
使用 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]"
评论
// Number Type [int, float literals ] var int = 77; var float = 77.7; console.log( int.toFixed(10) + '\t' + float.toFixed(10) ); // Object Type var number = new Number( 77 ); if( int != float ) console.log('Data Not Equal'); if( int == number && int !== number ) console.log('Data is Equal & Types vary');
我认为使用 ?操作员稍微干净一些。
var ? function_if_exists() : function_if_doesnt_exist();
这将检查不确定嵌套的变量是否未定义
function Undef(str)
{
var ary = str.split('.');
var w = window;
for (i in ary) {
try { if (typeof(w = w[ary[i]]) === "undefined") return true; }
catch(e) { return true; }
}
return false;
}
if (!Undef("google.translate.TranslateElement")) {
上面检查谷歌翻译函数 TranslateElement 是否存在。这相当于:
if (!(typeof google === "undefined"
|| typeof google.translate === "undefined"
|| typeof google.translate.TranslateElement === "undefined")) {
就我而言,我尝试了 if null,'', !variable,但它没有用。
请参阅下面的代码以从 html 字段中获取文本
var status=$(this).text(); //for example (for my case)
如果状态变量中没有值(无文本),我尝试将值“novalue”设置为状态变量。
以下代码有效。
if(status == false)
{
status='novalue';
}
当没有找到 satus 变量的文本时,上面的代码将“novalue”分配给 status 变量
评论
虽然是老手,但忘记的是他们应该包装他们的代码块,然后捕获错误,然后测试......
function checkup( t ){
try{
for(p in t){
if( p.hasOwnProperty( t ) ){
return true;
}
}
return false;
}catch(e){
console.log("ERROR : "+e);
return e;
}
}
因此,您真的不必事先检查潜在问题,只需抓住它,然后按照自己的意愿进行处理即可。
function isEmpty(val){
return !val;
}
但是这个解决方案是过度设计的,如果你不想以后修改函数以满足业务模型的需要,那么直接在代码中使用它会更干净:
if(!val)...
var myNewValue = myObject && myObject.child && myObject.child.myValue;
这永远不会引发错误。如果 myObject、child 或 myValue 为 null,则 myNewValue 将为 null。不会抛出任何错误
对于每个来这里提出类似问题的人,以下内容效果很好,我最近几年在我的图书馆里有它:
(function(g3, $, window, document, undefined){
g3.utils = g3.utils || {};
/********************************Function type()********************************
* Returns a lowercase string representation of an object's constructor.
* @module {g3.utils}
* @function {g3.utils.type}
* @public
* @param {Type} 'obj' is any type native, host or custom.
* @return {String} Returns a lowercase string representing the object's
* constructor which is different from word 'object' if they are not custom.
* @reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
* http://javascript.info/tutorial/type-detection
*******************************************************************************/
g3.utils.type = function (obj){
if(obj === null)
return 'null';
else if(typeof obj === 'undefined')
return 'undefined';
return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
};
}(window.g3 = window.g3 || {}, jQuery, window, document));
它可能是有用的。
数组中的所有值都表示您想要成为的内容(null、undefined 或其他内容),您可以在其中搜索您想要的内容。
var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1
评论
此函数检查,, ,和empty object {}
empty array []
null
undefined
blank string ""
function isEmpty(val) {
//check for empty object {}, array []
if (val !== null && typeof val === 'object') {
if (Object.keys(obj).length === 0) {
return true;
}
}
//check for undefined, null and ""
else if (val == null || val === "") {
return true;
}
return false;
}
var val={};
isEmpty(val) -> true
val=[];
isEmpty(val) -> true isEmpty(undefined) -> true isEmpty(null) -> true isEmpty(“”) -> true
isEmpty(false) -> false isEmpty(0) -> false
您可以直接使用相等运算符
<script>
var firstName;
var lastName = null;
/* Since null == undefined is true, the following statements will catch both null and undefined */
if(firstName == null){
alert('Variable "firstName" is undefined.');
}
if(lastName == null){
alert('Variable "lastName" is null.');
}
</script>
demo @ 如何使用 JavaScript 确定变量是 undefined 还是 null
尝试使用不同的逻辑。您可以使用下面的代码来检查所有四 (4) 个条件进行验证,例如 not null、not blank、not undefined 和 not zero,仅使用此代码 (!(!(变量)))在 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);
}
}
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;
}
在 ES6 中,带有 trim 来处理空格字符串:
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
}
评论
如果您使用的是 TypeScript
,并且不想考虑“值为 false
”,那么这就是适合您的解决方案:
第一:import { isNullOrUndefined } from 'util';
然后:isNullOrUndefined(this.yourVariableName)
请注意:如下所述,这现已弃用,请改用。文献value === undefined || value === null
评论
/** @deprecated since v4.0.0 - use "value === null || value === undefined" instead. */
try{
let vari = obj.propTest; // obj may be don't have propTest property
...
} catch(NullException){
// do something here
}
我认为使用 try catch 将避免任何空检查错误,即使在 Angular 或 JavaScript 中也是如此 只是捕获 null 异常并在其中进行处理。
评论
return val || 'Handle empty variable'
在很多地方都是一种非常好和干净的处理方式,也可以用来分配变量
const res = val || 'default value'
评论
true
val
false
const res = falsyValue ? true : falsyValue
我非常喜欢的一个解决方案:
让我们定义一个空白变量是 ,或者 ,或者如果它有长度,它就为零,或者如果它是一个对象,它就没有键: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)
)
}
返回:
- 真: , , , ,
undefined
null
""
[]
{}
- false:、、、、、、、、
true
false
1
0
-1
"foo"
[1, 2, 3]
{ foo: 1 }
评论
if (!value || value === '') { delete a.b[field]; } else { a.b[field] = {val: value, ... }; }
真空度
我不建议尝试定义或使用一个函数来计算整个世界中是否有任何值是空的。“空”的真正含义是什么?如果我有,应该返回吗?如果我有,应该返回吗?怎么样 - 这个列表只包含空,那么列表本身是空的吗?我想在这里提出一些关于javascript中“空洞性”(一个故意模糊的词,以避免预先存在的关联)的注释 - 我想争辩说,javascript值中的“空洞性”永远不应该被笼统地处理。let human = { name: 'bob', stomach: 'empty' }
isEmpty(human)
true
let reg = new RegExp('');
isEmpty(reg)
true
isEmpty([ null, null, null, null ])
真实性/虚假性
为了决定如何确定值的“空洞性”,我们需要适应 javascript 内在的、固有的价值观是“真实”还是“虚假”的意义。自然,都是“假的”。不太自然的是,这个数字(除了 之外没有其他数字)也是“假的”。最不自然的是:是虚假的,但 和 (和 , 和 ) 是真实的——尽管它们看起来都同样空洞!null
undefined
0
NaN
''
[]
{}
new Set()
new Map()
Null 与未定义
还有一些关于 vs 的讨论 - 我们真的需要两者来表达我们的程序中的空洞吗?我个人避免出现在我的代码中。我总是用它来表示“空虚”。不过,同样,我们需要适应 javascript 固有的如何和不同:null
undefined
undefined
null
null
undefined
- 尝试访问不存在的属性会给出
undefined
- 调用函数时省略参数会导致该参数接收:
undefined
let f = a => a;
console.log(f('hi'));
console.log(f());
- 具有默认值的参数仅在给定时接收默认值,而不是:
undefined
null
let f = (v='hello') => v;
console.log(f(null));
console.log(f(undefined));
对我来说,是空虚的明确能指;“本来可以填写的东西被故意留空了”。null
确实是一个必要的复杂性,它允许一些js功能存在,但在我看来,它应该始终留在幕后;而不是直接交互。例如,我们可以将其视为实现默认函数参数的 javascript 机制。如果您不向函数提供参数,它将收到一个值 。如果函数参数最初设置为 ,则默认值将应用于该参数。在这种情况下,是默认函数参数的关键,但它仍然在后台:我们可以实现默认参数功能,而无需引用:undefined
undefined
undefined
undefined
undefined
undefined
这是默认参数的糟糕实现,因为它直接与:undefined
let fnWithDefaults = arg => {
if (arg === undefined) arg = 'default';
...
};
这是一个很好的实现:
let fnWithDefaults = (arg='default') => { ... };
这是接受默认参数的糟糕方法:
fnWithDefaults(undefined);
只需改为执行此操作:
fnWithDefaults();
顺便说一句:您是否有一个具有多个参数的函数,并且您想提供一些参数,同时接受其他参数的默认值?
例如:
let fnWithDefaults = (a=1, b=2, c=3, d=4) => console.log(a, b, c, d);
如果要为其他 和 提供值并接受默认值,该怎么办?这似乎是错误的:a
d
fnWithDefaults(10, undefined, undefined, 40);
答案是:重构以接受单个对象:fnWithDefaults
let fnWithDefaults = ({ a=1, b=2, c=3, d=4 }={}) => console.log(a, b, c, d);
fnWithDefaults({ a: 10, d: 40 }); // Now this looks really nice! (And never talks about "undefined")
非通用真空度
我认为,空洞永远不应该以笼统的方式处理。相反,在确定数据是否空洞之前,我们应该始终严谨地获取有关我们数据的更多信息 - 我主要通过检查我正在处理的数据类型来做到这一点:
let isType = (value, Cls) => {
// Intentional use of loose comparison operator detects `null`
// and `undefined`, and nothing else!
return value != null && Object.getPrototypeOf(value).constructor === Cls;
};
请注意,此函数忽略了继承 - 它期望是 的直接实例,而不是 的子类的实例。我避免有两个主要原因:value
Cls
Cls
instanceof
([] instanceof Object) === true
(“数组是一个对象”)('' instanceof String) === false
(“字符串不是字符串”)
请注意,用于避免(模糊的)边缘情况,例如函数仍正确返回 (false) 和 (true)。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
if (isType(v, String)) {
/* v isn't generic in this block - It's a String! */
} else if (isType(v, Number)) {
/* v isn't generic in this block - It's a Number! */
} else if (isType(v, Array)) {
/* v isn't generic in this block - it's an Array! */
} else {
throw new Error('Expected String, Number, or Array');
}
- 始终使用“白名单”进行验证。如果您需要一个值,例如 String、Number 或 Array,请检查这 3 种“白色”可能性,如果 3 种可能性都不满足,则抛出 Error。我们应该能够看到,检查“黑色”的可能性并不是很有用:假设我们写了 - 这对于确保值不会通过非常有用,但是如果一个值确实通过,我们仍然对它几乎一无所知。通过此 null 检查的值仍然非常通用 - 它绝不是
null
!黑名单很难消除通用性。if (v === null) throw new Error('Null value rejected');
null
v
- 除非值为
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) ...
唯一的例外是用于表示某些功能。在这种情况下,说:“一个空洞的值”是有意义的:
null
if (val === null) ...
如果要避免在值为以下任何一项时获得 true,则根据 jAndy 的回答:
- 零
- 定义
- 南
- 空字符串 (“”)
- 0
- 假
一种可能避免获取真实值的可能解决方案如下:
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;
}
}
它的用途如下:
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!
}
除了这些情况之外,如果对象或数组为空,您可能希望返回 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;
}
}
如果要检查所有空格字符串 (“ ”),可以执行以下操作:
function isAllWhitespace(){
if (valueToCheck.match(/^ *$/) !== null) {
// Is all whitespaces!
return true;
} else {
// Is not all whitespaces!
return false;
}
}
注意:如果变量被声明为其中任何一个,则为空字符串、0、false、NaN、null 和 undefined 返回 true,因此它可能不是最佳使用方法。可以修改该函数以使用它来显示它已声明,但不可用。hasOwnProperty
这也包括空数组和空对象
null, 未定义, ' ', 0, [ ], { }
isEmpty = (value) => (!value || (typeof v === 'object' &&
Object.keys(value).length < 1));
看一下新的 ECMAScript Nullish 合并算子
您可以将此功能(运算符)视为在处理 or 时“回退”到默认值的一种方式。??
null
undefined
let x = foo ?? bar();
同样,上面的代码等效于以下内容。
let x = (foo !== null && foo !== undefined) ? foo : bar();
评论
if ((x ?? null) === null)
null
undefined
??=
name ??= 'bob'
name = (name !== null && name !== undefined) ? name : 'bob'
const isEmpty = value => (
(!value && value !== 0 && value !== false)
|| (Array.isArray(value) && value.length === 0)
|| (isObject(value) && Object.keys(value).length === 0)
|| (typeof value.size === 'number' && value.size === 0)
// `WeekMap.length` is supposed to exist!?
|| (typeof value.length === 'number'
&& typeof value !== 'function' && value.length === 0)
);
// Source: https://levelup.gitconnected.com/javascript-check-if-a-variable-is-an-object-and-nothing-else-not-an-array-a-set-etc-a3987ea08fd7
const isObject = value =>
Object.prototype.toString.call(value) === '[object Object]';
穷人的考验 😁
const test = () => {
const run = (label, values, expected) => {
const length = values.length;
console.group(`${label} (${length} tests)`);
values.map((v, i) => {
console.assert(isEmpty(v) === expected, `${i}: ${v}`);
});
console.groupEnd();
};
const empty = [
null, undefined, NaN, '', {}, [],
new Set(), new Set([]), new Map(), new Map([]),
];
const notEmpty = [
' ', 'a', 0, 1, -1, false, true, {a: 1}, [0],
new Set([0]), new Map([['a', 1]]),
new WeakMap().set({}, 1),
new Date(), /a/, new RegExp(), () => {},
];
const shouldBeEmpty = [
{undefined: undefined}, new Map([[]]),
];
run('EMPTY', empty, true);
run('NOT EMPTY', notEmpty, false);
run('SHOULD BE EMPTY', shouldBeEmpty, true);
};
测试结果:
EMPTY (10 tests)
NOT EMPTY (16 tests)
SHOULD BE EMPTY (2 tests)
Assertion failed: 0: [object Object]
Assertion failed: 1: [object Map]
评论
value.constructor === Object
value.constructor === Object
Null
{}
下面对我有用。请稍作改动以使其快速
function isEmpty(obj) {
if (!obj) return true;
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;
}
对于我的用例,大多数现有答案都失败了,如果将函数分配给变量或返回 NaN,则大多数返回空。帕斯卡的回答很好。
这是我的实现,请测试一下,如果你发现什么,请告诉我。你可以在这里看到我是如何测试这个函数的。
function isEmpty(value) {
return (
// Null or undefined.
(value == null) ||
// Check if a Set() or Map() is empty
(value.size === 0) ||
// NaN - The only JavaScript value that is unequal to itself.
(value !== value) ||
// Length is zero && it's not a function.
(value.length === 0 && typeof value !== "function") ||
// Is an Object && has no keys.
(value.constructor === Object && Object.keys(value).length === 0)
)
}
返回:
- 真: , , , , ,
undefined
null
""
[]
{}
NaN
new Set()
//
- 错误:、、、、、
true
false
1
0
-1
"foo"
[1, 2, 3]
{ foo: 1 }
function () {}
可选的链接运算符提供了一种方法,用于在引用或函数可能未定义或为 null 时简化通过连接对象访问值的过程。
let customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls" // detailed address is unknown
}
};
let customerCity = customer.details?.address?.city;
可以在可选链接之后使用空合并运算符,以便在未找到任何值时构建默认值:
let customer = {
name: "Carl",
details: { age: 82 }
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city
可能最简短的答案是
val==null || val==''
如果将 rigth side 更改为 ,则空数组将给出 false。证明val===''
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
更多细节(来源在这里==
)
奖励:原因比===
==
写得清晰易懂 可理解的代码,使用接受值的显式列表
val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)
function isEmpty(val){
return val===undefined || val===null || val==='' || (Array.isArray(val) && val.length===0)
}
// ------------
// 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
评论
(source here)
您始终可以使用 loadash 函数,例如 _.isNil 或 _.isUndefined。它们非常易于使用。
评论
function notEmpty(value){
return (typeof value !== 'undefined' && value.trim().length);
}
它还将检查空格 (' ') 以及以下内容:
- null ,undefined ,NaN ,空 ,字符串 (“”) ,0 ,false
尝试 Boolean() 和 isNaN()(用于数字类型)来检查变量是否有值。
function isEmpty(val) {
return typeof val === 'number' ? isNaN(val) : !Boolean(val);
}
var emptyVals = [undefined, null, false, NaN, ''];
emptyVals.forEach(v => console.log(isEmpty(v)));
- 您可以使用参数
- 成为数组的参数
- 滤波器
function validateAttrs(arg1, arg2, arg3,arg4){
var args = Object.values(arguments);
return (args.filter(x=> x===null || !x)).length<=0
}
console.log(validateAttrs('1',2, 3, 4));
console.log(validateAttrs('1',2, 3, null));
console.log(validateAttrs('1',undefined, 3, 4));
console.log(validateAttrs('1',2, '', 4));
console.log(validateAttrs('1',2, 3, null));
将仅返回 和 :false
undefined
null
return value ?? false
评论
false ?? false === false
false
false
!(0 ?? false) === true
您可以使用 nullish 合并运算符来检查 和 值。查看 MDN 文档??
null
undefined
null ?? 'default string'; // returns "default string"
0 ?? 42; // returns 0
(null || undefined) ?? "foo"; // returns "foo"
这是我检查数据是否为空的解决方案。
const _isEmpty = (data) => {
return (
// this way we can also check for undefined values. null==undefined is true
data == null ||
data == "" ||
(Array.isArray(data) && data.length === 0) ||
// we want {} to be false. we cannot use !! because !!{} turns to be true
// !!{}=true and !!{name:"yilmaz"}=true. !! does not work ofr objects
(data.constructor === Object && Object.keys(data).length === 0)
);
};
我认为这使您的代码看起来更简单
检查变量 IS 或undefined
null
var a=undefined, b=null, c='hello world', d;
if(a !== (a ?? {})) { /**/ } // true
if(b !== (b ?? {})) { /**/ } // true
if(c !== (c ?? {})) { /**/ } // false
if(d !== (d ?? {})) { /**/ } // true
检查变量是否为 NOT 或undefined
null
var a=undefined, b=null, c='hello world', d;
if(a === (a ?? {})) { /**/ } // false
if(b === (b ?? {})) { /**/ } // false
if(c === (c ?? {})) { /**/ } // true
if(d === (d ?? {})) { /**/ } // false
仅使用“nullish coalescing”检查未定义和 null
if ((myVariable ?? undefined) !== undefined) {
// handle myVariable has a value, including 0 or ""
}
else {
// handle undefined or null only
}
从 Chrome 控制台
{const x=undefined; (x ?? undefined) !== undefined}
false
{const x=null; (x ?? undefined) !== undefined}
false
{const x=0; (x ?? undefined) !== undefined}
true
{const x=""; (x ?? undefined) !== undefined}
true
{const x={}; (x ?? undefined) !== undefined}
true
{const x=[]; (x ?? undefined) !== undefined}
true
{const x="a"; (x ?? undefined) !== undefined}
true
评论
(truthy statement) ? true : false;
(truthy statement);
if (hungry) …
if (hungry === true) …
!!value