有没有更简单的方法可以做到这一点,那就是JavaScript:
if (routine !== null && routine.exercises !== undefined && routine.exercises.length > 0) {
// Do Something
}
例如在Dart中,我可以这样做:
if (routine?.exercises?.length > 0 ?? 0) {
// DO Something
}
这意味着例程是null还是例程.exercises是null还是例程.exercises.length不大于0,则仅将0作为表达式
答案 0 :(得分:2)
你可以
if (routine && routine.exercises && routine.exercises.length) ...
或更短,但可能更难阅读,请使用默认值
if (((routine || {}).exercises || []).length) ...
示例:
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);
答案 1 :(得分:0)
0
undefined
和null
都是虚假的值,您不需要进行比较就可以直接比较。
if (routine && routine.exercises && routine.exercises.length) {
// Do Something
}