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

标签 javascript

我正在创建一个函数来检查给定值是否为空,如果未定义、等于空字符串或长度为零,则它将返回 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))


   

添加 - 什么是未捕获引用错误:“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/

相关文章:

javascript - 在 .js 文件中使用 ASP.Net 标签?

javascript - 正则表达式第一次出现

javascript - Node : Run Mysql queries synchronously

javascript - 如何从 JSON 对象中提取数据

javascript - 在 FireFox 中监听历史事件?

javascript - 防止事件被不必要地触发

javascript - 如果此人不符合资格,如何使我的 JavaScript 提示重定向到其他页面

javascript - polymer ,基于对象评估元素

javascript - googlebot 可以做基本的 javascript 吗?

javascript - 如何在 Vue.js 中加载 emscripten 生成的模块以使用其功能?