代码之家  ›  专栏  ›  技术社区  ›  Joe Moore

如何检测数组中未定义的变量?

  •  1
  • Joe Moore  · 技术社区  · 6 年前

    "" 以便在输出时不显示它们。我的版本又笨重又太大,我在想如何用一个函数使它变小。

    代码:

    var fifteenSecond = `Your 15s highscore: ${maxesTime[15]}wpm`
    var thirtySecond = `Your 30s highscore: ${maxesTime[30]}wpm`
    var sixtySecond = `Your 60s highscore: ${maxesTime[60]}wpm`
    
      if (maxesTime[15] === undefined) {
        fifteenSecond = ""
      } else if (maxesTime[30] === undefined) {
        thirtySecond = ""
      } else if (maxesTime[60] === undefined) {
        sixtySecond = ""
      }
    
    console.log(`${sixtySecond}}\n${thirtySecond}\n${fifteenSecond}`);
    

    提前谢谢你,

    2 回复  |  直到 6 年前
        1
  •  2
  •   Alessio Cantarella    6 年前

    你可以简单地使用 for 检查所有财产 i maxesTime . 如果你增加一个新的“最长时间”( 例如

    let maxesTime = {
      '15': 100,
      '30': null,
      '45': undefined,
      '60': 400
    };
    for (let i in maxesTime) {
      if (maxesTime[i]) {
        console.log(`Your ${i}s highscore: ${maxesTime[i]}wpm`);
      }
    }
        2
  •  1
  •   tdphut    6 年前

    我的建议是:

    function getRecord(seconds, maxesTime) {
      return maxesTime[seconds] ? 
        `Your ${seconds}s highscore: ${maxesTime[seconds]}wpm`
        : '';
    }