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

JSON 2016-10-17 13:51:56 151196

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

首先什么是is not defined?

从字面意思上来讲就是未定义,也就是未申明。就是这个变量(对象)压根就没有。如下:

console.log(sojson);//sojson is not defined

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

is not defined 和 undefined 区别。

我们大多数人都知道 undefined  ,却不知道 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

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

所以总结一下: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  ,就不会往下执行了,所以要分开去处理。


版权所属:SO JSON在线解析

原文地址:https://www.sojson.com/blog/182.html

转载时必须以链接形式注明原始出处及本声明。

本文主题:

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

关于作者
一个低调而闷骚的男人。
相关文章
Javascript 判断域名合法性,JS域名格式检测
JS判断网页广告被屏蔽解,广告终结者、AdGuard插件判断并提示
ZeroClipboard.config is not a function ZeroClipboard is not defined 错误解决
js问号的作用意义
如何判断字符串是JSON数组还是JSON对象
Httpclent 请求限制,判断返回类型返回数据大小
怎么查询网站备案号以及如何判断备案号的真假
IE浏览器判断判断IE版本的HTML语句详解,如:[if lte IE 9]……[endif]
IOS urldecode 如何解码后,解码后“+”(加号)空格处理方式
HTMLJSON如何互转
最新文章
PHP if/else/elseif 语句 58
HTML5 Canvas弧线教程 52
Java赋值运算符 118
XML内部实体和外部实体 201
Java面向对象编程概念 177
PHP回显语句 127
Linux—文件树 135
C语言while循环和do while循环 150
Python元组剖析 209
MySQL触发器教程 342
最热文章
最新MyEclipse8.5注册码,有效期到2020年 (已经更新) 682603
苹果电脑Mac怎么恢复出厂系统?苹果系统怎么重装系统? 674741
免费天气API,全国天气 JSON API接口,可以获取五天的天气预报 602586
免费天气API,天气JSON API,不限次数获取十五天的天气预报 579397
Jackson 时间格式化,时间注解 @JsonFormat 用法、时差问题说明 553093
我为什么要选择RabbitMQ ,RabbitMQ简介,各种MQ选型对比 509458
Elasticsearch教程(四) elasticsearch head 插件安装和使用 480074
Jackson 美化输出JSON,优雅的输出JSON数据,格式化输出JSON数据... ... 264851
Java 信任所有SSL证书,HTTPS请求抛错,忽略证书请求完美解决 244332
Elasticsearch教程(一),全程直播(小白级别) 225657
支付扫码

所有赞助/开支都讲公开明细,用于网站维护:赞助名单查看

查看我的收藏

正在加载... ...