考虑未定义的变量

时间:2015-10-24 18:53:52

标签: javascript conditional

我对如何解释未定义的变量感到有点困惑(我现在还不确定你是否可以)。我尝试使用下面代码底部附近的if else语句(被注释掉的行)。

这个想法是,如果请求歌曲的人不是参与者或狗,则应该运行相关联的警报。一旦调用该函数,解释器就会识别出" guy"没有定义,这打破了一切。我可以很容易地解释一个未完成的变量,但是可以考虑一个未定义的变量吗?我尝试了各种各样的东西,但似乎它实际上并不可能。

有什么想法吗?

function Attendee(name) {
  this.name = name;
}

var dan = new Attendee('Dan');
var christer = new Attendee('Christer');
var mooney = new Attendee('Mooney');

function Dog(name) {
  this.name = name;
}

var murphy = new Dog('Murphy');
var lotty = new Dog('Lotty');
var willow = new Dog('Willow');


var songs = ['Vacationer - Farther', 'Tapes - Crowns', 'Lapalux - Straight Over My Head', 'Ben Khan - Youth', 'Touch Sensitive - Pizza Guy', 'Atu - The Duo', 'XO - The Light', 'Sohn - Artifice', 'Cambio Sun - Mad As They Come', 'Majical Cloudz - Your Eyes', 'Chet Faker - Talk is Cheap', 'Raffertie - Build Me Up', 'Oceaan - Candour', 'Oscar Key Sung - All I Could Do', 'Kenton Slash Demon - Harpe', 'Odesza - How Did I Get Here?', 'Tiger Tsunami - Antarctica', 'Gallant - Open Up'];

  var addSong = function(song, requester) {

    if (requester instanceof Attendee) {
      if (songs.indexOf(song) >= 0) {
        alert('Thanks, we\'ve already got that one!');
      } else {
        songs.push(song);
      }
    } else if (requester instanceof Dog) {
      alert(requester.name + ', you\'re a dog! You can\'t request a song!');
//    } else if () {
      alert('Who invited you?');
    }

  };

addSong('Vacationer - Farther', guy);

1 个答案:

答案 0 :(得分:2)

在引用变量之前,您必须检查变量是否已定义

if (typeof guy !== "undefined") {
   addSong('Vacationer - Farther', guy);
} else {
   alert("Who invited you?");
}

如果您希望addSong被调用,即使guy未定义。

   addSong('Vacationer - Farther', typeof guy !== 'undefined' && guy);

如果false未定义,那么guy将作为请求者传递。