gpt4 book ai didi

Javascript : How to process function's argument even if it undefined

转载 作者:行者123 更新时间:2023-11-29 18:41:40 26 4
gpt4 key购买 nike

我正在创建一个函数来检查给定值是否为空,如果未定义、等于空字符串或长度为零,它将返回 true。这是我所做的

isEmpty(value){
if(typeof(value)=='undefined'){
return true;
}
else if(value==''||value.length==0){
return true;
}
return false;
}

但是当我评估一些 undefined variable 时,例如 isEmpty(foo) 它会抛出一个 Uncaught ReferenceError ,但我想返回 true,该怎么做?

function isEmpty(value) {
if (typeof(value) == 'undefined') {
return true;
} else if (value == '' || value.length == 0) {
return true;
}
return false;
}

console.log(isEmpty(value))

最佳答案

你正在理解Undefined错了

Undefined means a variable has been declared, but the value of that variable has not yet been defined(Not assigned a value yet). For example:

function isEmpty(value){

// or simply value===undefined will also do in your case
if(typeof(value)==='undefined'||value==''||value.length==0){
return true;
}
return false;

}
let foo; // declared but not assigned a value so its undefined at the moment
console.log(isEmpty(foo))


添加 - 什么是未捕获的 ReferenceError:“x”未定义。

There is a non-existent variable referenced somewhere. This variable needs to be declared , or you need make sure it is available in your current script or scope.

很明显你没有在上下文中的任何地方引用你的变量,所以你得到了那个异常。 Follow Up Link

这是通过捕获引用错误来检查变量是否在范围内或是否已声明的方法

// Check if variable is declared or not

//let value;
try {
value;
} catch (e) {
if (e.name == "ReferenceError") {
console.log("variable not declared yet")
}


}

// or the function approach


function isEmpty(value){

// or simply value===undefined will also do in your case
if(typeof(value)==='undefined'||value==''||value.length==0){
return true;
}
return false;

}


try {
isEmpty(value);
} catch (e) {
if (e.name == "ReferenceError") {
console.log("variable not declared yet")
}
}

关于Javascript : How to process function's argument even if it undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56591694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com