obj = obj || {} 分析这个代码的起到的作用
2024-08-27 02:49:40
情况一:
<script>
function test(obj) {
console.log(obj.value)
} function student() {
this.value = "foo";
}
var obj = new student(); test(obj);
</script>
结果:正常输出
情况二:假如obj为null或者undefined呢?
<script>
function test(obj) {
console.log(obj.value)
} function student() {
this.value = "foo";
}
var obj = null;
test(obj);
</script>
结果:报错
总结:只要加入以下这段代码就可以判断出对象是否为null或者undefined,避免报错。
obj = obj || {};
即使是null,也不会报错:
一开始我看代码也没明白是有什么作用,实践之后才明白,加入上面这行代码之后,即使是null都不会报错,只是为undefined。
最新文章
- VS2012 还原默认设置
- 神盾解密工具 之 解密 “ PHP 神盾解密工具 ”
- MySQL命令实例
- switch 的一些事
- 第26章 创建型模式大PK
- LeetCode(76) Minimum Window Substring
- java中String类型转换方法
- [Android]Fragment源代码分析(二) 状态
- 题目:[NOIP1999]拦截导弹(最长非递增子序列DP) O(n^2)和O(n*log(n))的两种做法
- Homestead PHP7安装phpredis扩展
- # ? &; 号在url中的的作用
- js返回顶部封装 简洁
- 专业辟谣----ThinkSNS不仅仅是微博程序!
- 在Ubuntu虚拟机搭建数据库系统
- Java基础--Java---IO流------GUI(布局)、Frame、事件监听机制、窗体事件、Action事件、鼠标事件、对话框Dialog、键盘事件、菜单
- VBox修改uuid
- django的小操作,查询效率up, 引用art-template模板+djangorestframework
- Django基础九之中间件
- 读《锋利的jQuery》中first-child时的一个细节
- **PHP SimpleXML 使用详细例子
热门文章
- 基于grafana+prometheus构建Flink监控
- 【Leetcode_easy】893. Groups of Special-Equivalent Strings
- Docker 安装运行MySQL
- 欧姆龙PLC_CP1H_CRC校验
- 用pytorch1.0搭建简单的神经网络:进行多分类分析
- [SQL] - Attempted to read or write protected memory. This is often an indication that other memory is corrupt. 问题之解决
- C++打印水仙花数
- 理解atoi()函数
- git彻底删除或变更子模块
- echarts饼状图位置设置