💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
> 文档版本:1.0.1 > 编辑时间:2021.11.17 | 日期 | 变更说明说明 | 变更人 | | --- | --- | --- | | 2021.11.17 | js变量判断使用规范 | mike | ### js变量判断使用规范 > **多层级判断变量是否为空的情况,一定要先判断它的上级是否是空** > 原因:如果接口返回来的数据是多层级的数据,只判断最最内部的数据,一担数据返回的上层是空,就会导致js抛异常,导致页面报错,不执行。 > 例如:判断对象data.info.cardNo 如果info是空,那么就对导致js报错,这种情况正常写法如下: ``` if(!!data && !!data.info && data.info.cardNo == '.......') ``` ### 判断一个对象是否是空 #### js中 ! 的用法是比较灵活的,它除了做逻辑运算常常会用!做类型判断,可以用!与上对象来求得一个布尔值、!可将变量转换成boolean类型,null、undefined和空字符串取反都为true,其余都为false ``` !null = true !undefined=true !''=true !100 = false !'abc'=false ``` > 根据如上的总结判断一个变量是否为空用如下写法: ``` if(!!a) ``` > 不要在用如下写法: ``` if(a!=null && a!=undefined && a != '') ``` ### 下面的是一个列子,大家可以自己尝试一下 ``` <template> <div id="app" style="background: rgb(241, 247, 252);"> <van-button type="primary" @click="testAction">测试变量</van-button> </div> </template> <script> export default { data () { return { obj: {}, str: '', arr: [] } }, mounted () { }, methods: { testAction () { try { if (this.obj) { // 不会报错 console.log('obj--可以判断') } } catch (e) { console.log('报错了') } try { if (this.w) {} } catch (e) { console.log('this.w 报错了') } try { if (this.w.b) {} } catch (e) { console.log('this.w.b 报错了') } try { if (this.arr) {} } catch (e) { console.log('this.arr 报错了') } try { if (this.arr[0].b) {} } catch (e) { console.log('this.arr[0].b 报错了') } try { if (this.obj.a) {} // 不会报错 } catch (e) { console.log('this.obj.a 报错了') } try { if (this.obj.a.b) {} // 会报错 } catch (e) { console.log('this.obj.a.b 报错了') } try { if (!!this.obj && !!this.obj.a && this.obj.a.b) {} // 不会报错 } catch (e) { console.log('this.obj.a.b 报错了') } try { if (!!this.obj && !!this.obj.a && this.obj.a.b) {} } catch (e) { console.log('this.obj.a.b 报错了') } } } } </script> ``` ![](https://img.kancloud.cn/01/67/01679f7edd23878232c4057602a03150_809x534.png)