JavaScript 函数,用于检查变量是否存在以避免错误
JavaScript Function to check for existence of a variable to avoid error
如何在 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 ) {
}
相关文章:
- JavaScript setInterval函数:是否存在错误
- 这个get方法似乎可以工作,但控制台中存在错误
- 如果字符串中存在错误,请检查数组中的char
- ASP.Net MVC 5 Ajax 请求在编辑页面上不存在错误__RequestVerificationToken
- 在 webpack -p 上的 ./app/index.js 中存在错误
- Dropzone,如果存在错误,如何不处理队列
- 发送到谷歌应用脚本的谷歌电子表格对象包装器中是否存在错误
- 我的 jQuery 滑块运行良好,但存在错误,它有时不会在下次或上一次单击时显示图像
- 我将 javascript 验证添加到我的登录控件中,尽管存在错误
- Firefox中的JSON.parse是否存在错误
- 用Javascript处理TestComlete中的对象不存在错误
- 如何循环浏览每个图像并在casperjs脚本中检查其是否存在错误
- 文件不存在错误,package.json错误
- 由于回调结构中可能存在错误,无法使超时工作
- 在Javascript中将数字转换为字符串时是否存在错误
- Q承诺链存在错误后的承诺链
- __proto__属性的MDN解释中可能存在错误
- angular.js 1.4.8错误:$resource:badcfg正常浏览器中存在错误,但不存在隐身
- 针对不同上下文的原型的IE9中的JavaScript存在错误
- SyntaxError:JSON.parse:使用d3.js的JSON数据的第2行第14列的字符串文字中存在错误的控制字