是否有一个通用的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 (typeof(value) !== "undefined" && value)
or
if (typeof value !== "undefined" && value)
其他回答
这将检查不确定嵌套的变量是否未定义
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")) {
上面检查Google翻译函数TranslateElement是否存在。这相当于:
if (!(typeof google === "undefined"
|| typeof google.translate === "undefined"
|| typeof google.translate.TranslateElement === "undefined")) {
这是我检查数据是否为空的解决方案。
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)
);
};
var myNewValue = myObject && myObject.child && myObject.child.myValue;
这永远不会抛出错误。如果myObject、child或myValue为空,则myNewValue将为空。不会引发任何错误
可以直接使用相等运算符
<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确定变量是否未定义或为空
仅使用“空值合并”检查未定义和空值
if ((myVariable ?? undefined) !== undefined) {
// handle myVariable has a value, including 0 or ""
}
else {
// handle undefined or null only
}
来自铬控制台
{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