我对如何解释一个未定义的变量有些困惑(我不确定此时您是否可以)。我正在尝试使用以下代码(注释掉的行)底部附近的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);

最佳答案

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

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


如果您希望即使未定义addSong都调用您的guy

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


如果未定义false,则它将通过guy作为请求者。

关于javascript - 考虑 undefined variable ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33322049/

10-12 23:33