首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >更简单的写法是: if (routine !== null && routine.exercises !== undefined && routine.exercises.length > 0)

更简单的写法是: if (routine !== null && routine.exercises !== undefined && routine.exercises.length > 0)
EN

Stack Overflow用户
提问于 2019-04-03 23:48:10
回答 2查看 54关注 0票数 2

有没有一种更简单的方法是使用JavaScript:

代码语言:javascript
运行
复制
    if (routine !== null && routine.exercises !== undefined && routine.exercises.length > 0) {
        // Do Something
    }

例如,在Dart中,我可以这样做:

代码语言:javascript
运行
复制
    if (routine?.exercises?.length > 0 ?? 0) {
        // DO Something
    }

这意味着如果例程为null或routine.exercises为null或routine.exercises.length不大于0,则仅将0作为表达式

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-03 23:55:39

你可以做到

代码语言:javascript
运行
复制
if (routine && routine.exercises && routine.exercises.length) ...

或更短,但可能更难阅读,使用默认值

代码语言:javascript
运行
复制
if (((routine || {}).exercises || []).length) ...

示例:

代码语言:javascript
运行
复制
function test(routine) {
  if (routine && routine.exercises && routine.exercises.length) {
    console.log('passed with', JSON.stringify(routine));
  }
  if (((routine || {}).exercises || []).length) {
    console.log('passed with', JSON.stringify(routine));
  }
}

test({ exercises: [1] });
test({});
test(undefined);

票数 2
EN

Stack Overflow用户

发布于 2019-04-03 23:52:33

0undefinednull都是假值,你不需要比较,直接把它们放进去就行了。

代码语言:javascript
运行
复制
if (routine && routine.exercises && routine.exercises.length) {
        // Do Something
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55499256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档