JavaScript有没有更简单的方法可以做到这一点:

    if (routine !== null && routine.exercises !== undefined && routine.exercises.length > 0) {
        // Do Something
    }


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

    if (routine?.exercises?.length > 0 ?? 0) {
        // DO Something
    }


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

最佳答案

你可以做

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);

10-06 00:18