html 判断undefined,JS中 “is not defined” 如何判断defined,defined和undefined 的区别

JS中 “is not defined” 我今天找了一些资料和自己试验了各种方法,都不能得到正解,故写了这个问题的解决方案。

首先什么是is not defined?

从字面意思上来讲就是未定义,也就是未申明。就是这个变量(对象)压根就没有。如下:console.log(sojson);//sojson is not defined

可能还一知半解,我们继续往下看。

is not defined 和 undefined 区别。var so;

console.log(so);//undefined

console.log(so.a);//so.a is undefined

这个时候输出的是undefined。访问变量的属性就会提示is undefined就是这个变量so未定义值(类型);

而defined呢,如下:console.log(so);//so is not defined

其实如果理解一下其实就是未申明。也就是可以理解变量的过程是,先声明后赋值,在赋值的过程中确定了这个变量的类型。

6f86a59e956a37bd680e046f33ec0f4b.png

所以总结一下:is not defined 优先于 undefined ,也就是先判断这个对象是否申明了,如果没申明直接就 is not defined,如果已经申明,那么再看有没有赋值(类型),如果没有那么就是 undefined 或者 访问对象的属性就是 is undefined 。

is not defined 如何避免

比如我们常用的jquery,如果出现了jQuery is not defined ,或者$ is not defined ,那么我们按以下步骤来排查:是否引入了jQuery(注意是否404)。

jQuery是否在依赖jQuery的js之前引用(因为js加载是自上而下加载)。

是否过多引入jQuery,或者引入多个版本的jQuery。

我们自己定义对象的时候,对外要提供方法,如下://申明局部变量 so。

var so = {

a : function(){};

}

//对外提供访问。

window.so = so;

如何判断 undefined。

undefined 很好判断,如下:var sojson;

console.log(sojson == undefined);//true

console.log(sojson === undefined);//true;

console.log(typeof sojson == 'undefined');//true

console.log(typeof sojson === 'undefined');//true

console.log(!sojson);//true

//... ...

如何判断is not defined

我在网上没找到合适的资料来判断“is not defined”,我项目中因为是公共js需要解决,对象是否定义。都不好判断。所以我用比较low的方式来判断的,如果你有好的点子,请留言或者告知我,我加上。try{

var x = sojson.demo;

}catch(e){

console.log(e.message);//sojson is undefined

}

因为抛出了Exception,所以能catch,进入了catch模块。如果有多个,请分开cache,如下:try{

var x = sojson.demo;

}catch(e){

console.log(e.message);//sojson is undefined

}

try{

var y = sojson.y;

}catch(e){

console.log(e.message);//sojson is undefined

}

因为出现一个Exception,就不会往下执行了,所以要分开去处理。

如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。

¥我需要走的更远,点击我 赞助。

如果还有疑问,点击我加群,为你提供最好的解答。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值