JavaScript 函数,用于检查变量是否存在以避免错误

JavaScript Function to check for existence of a variable to avoid error

本文关键字:存在 错误 是否 变量 函数 用于 检查 JavaScript      更新时间:2023-09-26

如何在 JavaScript 中创建一个实用程序帮助函数来检查变量是否存在以避免错误Uncaught ReferenceError: testVar is not defined

以下是我正在尝试但失败的!

/**
 * Utility Helper Functions
 */
var Utility = {
    /**
     * Check if a variable is empty or not
     * @param mixed value - variable to check if it is empty and exist
     * @return Boolean - true/false if a variable is empty or not?
     */
    isEmpty: function(value){
      //return (value == null || value === '');
      return (typeof value === 'undefined' || value === null);
    },
}
// comment var test out so it will not exist for test
//var testVar = 'dgfd';
// Uncaught ReferenceError: testVar is not defined
alert(Utility.isEmpty(testVar));

您无法在isEmpty函数中处理此问题,因为它会在您进入函数内部之前抛出错误。

您可以使用尝试/捕获,但这会破坏函数的目的。

您可以简化事情并删除整个函数(不需要),如下所示:

if (typeof testVar !== "undefined") {
  console.log('The variable exists');
}

对象, 数组

if( foo instanceof Array ) { 
}