gpt4 book ai didi

javascript - 考虑 undefined variable

转载 作者:行者123 更新时间:2023-12-02 15:30:54 28 4
gpt4 key购买 nike

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

这个想法是,如果请求歌曲的人不是与会者或狗,则应该运行相关的警报。一旦调用该函数,解释器就会识别出“guy”未定义,这会破坏一切。我可以轻松地解释一个 undefined variable ,但是是否可以解释一个 undefined variable ?我尝试过各种方法,但似乎实际上不可能。

有什么想法吗?

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?");
}

如果您希望在 guy 未定义的情况下调用 addSong

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

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

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com