如何在javascript中处理'undefined' [英] How to handle 'undefined' in javascript

查看:168
本文介绍了如何在javascript中处理'undefined'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在JavaScript中检测未定义的对象属性

来自以下javascript示例

From the below javascript sample

 try {
    if(jsVar) {
     proceed();
      }
 }catch(e){
      alert(e);
 }

这个jsVar在另一个js罚款中被声明并初始化。

this jsVar is declared and initialed in another js fine.

问题是当代码在执行另一个文件(声明和启动的文件)之前执行时,代码会抛出未定义的错误。这就是它被try和catch包围的原因。

The problem is that code throws undefined error when this code is executed before the other file (where its declared and initiated) is executed. That is why it is surrounded by try and catch.

处理这个未定义的错误比尝试catch更好吗?

Whats the best way to handle this undefined error than try catch?

推荐答案

你可以用

if (typeof(jsVar) == 'undefined') {
  ...
}

这篇关于如何在javascript中处理'undefined'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆