有没有一种更简单的方法是使用JavaScript:
if (routine !== null && routine.exercises !== undefined && routine.exercises.length > 0) {
// Do Something
}例如,在Dart中,我可以这样做:
if (routine?.exercises?.length > 0 ?? 0) {
// DO Something
}这意味着如果例程为null或routine.exercises为null或routine.exercises.length不大于0,则仅将0作为表达式
发布于 2019-04-03 23:55:39
你可以做到
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);
发布于 2019-04-03 23:52:33
0,undefined和null都是假值,你不需要比较,直接把它们放进去就行了。
if (routine && routine.exercises && routine.exercises.length) {
// Do Something
}https://stackoverflow.com/questions/55499256
复制相似问题