判断Javascript变量是否为空 undefined 或者null(附样例)
2024-10-08 02:58:04
1.变量申明未赋值
var type; //type 变量未赋值
1. type==undefined //true
2. type===undefined //true
3. typeof(type)=='undefined' //true
4. typeof(type)==='undefined' //ture
5. typeof type == 'undefined' //和第3种等价,true
6. typeof type === 'undefined' //和第4种等价,true
7. type==null //true
8. type===null //false
注: typeof type 的值是"undefined",(typeof 返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined")。
2.变量未申明
1. type1==undefined //Error: Uncaught ReferenceError: type1 is not defined at <anonymous>:1:1
2. type1===undefined //Error
3. typeof(type1)=='undefined' //true
4. typeof(type1)==='undefined' //ture
5. typeof type1 == 'undefined' //和第3种等价,true
6. typeof type1 === 'undefined' //和第4种等价,true
7. type1==null //Error: Uncaught ReferenceError: type1 is not defined at <anonymous>:1:1
8. type1===null //Error: Uncaught ReferenceError: type1 is not defined at <anonymous>:1:1
3.JavaScript undefined 属性
定义和用法
undefined 属性用于存放 JavaScript 的 undefined 值。
说明
无法使用 for/in 循环来枚举 undefined 属性,也不能用 delete 运算符来删除它。
undefined 不是常量,可以把它设置为其他值。
当尝试读取不存在的对象属性时也会返回 undefined。
提示和注释
提示:只能用 === 运算来测试某个值是否是未定义的,因为 == 运算符认为 undefined 值等价于 null。
注释:null 表示无值,而 undefined 表示一个未声明的变量,或已声明但没有赋值的变量,或一个并不存在的对象属性。
最新文章
- Hi, there!
- php ffmpeg
- UITextField实现左侧空出一定的边距
- CNContact对通讯录的基本使用(增删改查)
- css中的继承、层叠、样式优先级机制
- ASP.NET 上传图片添加文字、Logo水印
- POJ 3126 Prime Path 解题报告(BFS &; 双向BFS)
- ImageView一例
- ProxyCreationEnabled 和 LazyLoadingEnabled 的关系
- C#高级编程随笔
- 15个nosql
- CentOS7 部署 tomcat
- MySQL常见建表选项以约束
- vue调试工具vue-devtools安装及使用
- Redis docker安装和主要功能
- SpringBoot启动源码探究---getRunListener()
- SpringBoot------全局异常捕获和自定义异常
- VS Code 管理 .NET Core解决方案
- Java实现Socket通信
- Python Web学习笔记之多线程编程