是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
当前回答
对于我的案例,我尝试了if null,“”!变量,但它不起作用。
查看下面的代码以从html字段获取文本
var status=$(this).text(); //for example (for my case)
如果状态变量中没有值(没有文本),我试图将值“novalue”设置为状态变量。
以下代码有效。
if(status == false)
{
status='novalue';
}
当没有找到satus变量的文本时,上面的代码将“novalue”分配给状态变量
其他回答
function isEmpty(value){
return (value == null || value.length === 0);
}
对于
undefined // Because undefined == null
null
[]
""
和零参数函数,因为函数的长度是它所使用的声明参数的数量。
要禁止后一个类别,您可能只需要检查空白字符串
function isEmpty(value){
return (value == null || value === '');
}
Null或空白
function isEmpty(value){
return (value == null || value.trim().length === 0);
}
对于每一个有类似问题的人来说,以下内容非常有用,我在过去的几年里都把它放在了我的图书馆里:
(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));
根据jAndy的回答,如果该值为以下任一值,那么如果您想避免为真:
无效的未定义NaN公司空字符串(“”)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:
对象:{}(使用ECMA7+)阵列:[](使用ECMA 5+)
你可以这样做:
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;
}
}
注意:如果变量被声明为空字符串中的任何一个,hasOwnProperty对于空字符串(0、false、NaN、null和undefined)返回true,因此这可能不是最好的用法。可以修改该函数以使用它来显示它已声明,但不可用。
我认为使用?操作员稍微干净一点。
var ? function_if_exists() : function_if_doesnt_exist();
如果变量尚未声明,则无法使用函数测试未定义,因为会出现错误。
if (foo) {}
function (bar) {}(foo)
如果尚未声明foo,则两者都将生成错误。
如果要测试变量是否已声明,可以使用
typeof foo != "undefined"
如果您想测试foo是否已声明,并且它有一个值,您可以使用
if (typeof foo != "undefined" && foo) {
//code here
}