javascript - 如何处理未定义的参数?
问题描述
我正在开发一个角度应用程序。作为其中的一部分,我想处理某个参数未定义的情况。
我的代码
myImage() {
console.log('test')
console.log(typeof(this.ahuObservables.on_off_status))
this.myValue = this.myObservables.status
console.log(typeof(this.myValue))
if (this.myValue == null)
{
console.log('undefined')
this.ahuValue = 0
}
else{
// do something
}
getDataRealTime()
{
console.log('Making a request')
this.SocketService.socket_connection()
.subscribe(
(data1: any) => {
console.log(data1)
let data11 = JSON.parse(data1)
this.myObservables = new My_Observables()
this.myObservables.status = data11['status']
console.log('variables parsed')
}
)
}
this.myObservables.status
在 api 调用中分配。因此,当我的 api 不工作时,我希望我的myValue
变量为 0。我尝试检查 null、未定义但如果 myObservables.status 未定义,我无法分配默认值。我的第二个 console.log 也没有打印任何内容安慰。有人可以帮我吗?
谢谢。
解决方案
您可以通过添加来检查 if 是否this.myValue
有一个假if(!this.myValue)
值,然后 if 语句将仅在 this.myValue 的值为 0、空字符串、未定义或 null 时执行。
myImage() {
console.log('test')
console.log(typeof(this.ahuObservables.on_off_status))
this.myValue = this.myObservables.status
console.log(typeof(this.myValue))
if (!this.myValue)
{
// this part of the code will be executed if this.myValue is 0, empty string, undefined or null
console.log('undefined')
this.ahuValue = 0
}
else{
// do something
}
推荐阅读
- yaml - 如何在 Swagger 的 YAML 中创建相同类型的嵌套对象数组?
- android - 蓝牙扫描方法 - PendingIntent 或 ScanCallback?
- apache-beam - 分组然后取消分组会导致光束 TestPipeline 上的所有事件丢失
- ruby - Ruby:如何知道是否有任何祖先已覆盖#initialize 以有条件地调用`super`
- flutter - 保存 Flutter 应用程序的完整状态
- cypress - 使用环境变量 (process.env) 覆盖 Cypress.config().baseUrl
- java - 如何在 Java SpringBoot 中拦截/禁用 HTTP Trace 方法
- html - css span 标签高度排序
- php - PHP在html网页上的不同时间显示不同的图像
- c# - 为什么我的获取数据查看的是旧数据库数据而不是更新的数据库数据?