3 回答
TA贡献1845条经验 获得超8个赞
您必须在函数外部声明变量并将它们设置在函数内部。否则它们的值在每次函数调用中都会被重置。
尝试这个:
var oldEmoji = '';
var emoji = '';
var emojiList = [";)", ":D", "xD", ":O", ":X", ":P"];
function randEmoji() {
oldEmoji = emoji;
emoji = emojiList[Math.floor(Math.random() * emojiList.length)];
if (oldEmoji == emoji) {
randEmoji();
} else {
console.log(emoji);
}
}
var i = 0;
while (i < 20) {
randEmoji();
i += 1;
}
TA贡献1843条经验 获得超7个赞
问题在于函数作用域的任何局部变量(意味着在函数内部声明)在函数完成执行后都会被丢弃。因此,每次运行该函数emoji并oldEmoji从undefined
一种解决方案是将其中一个声明移动到父范围,如下所示:
var oldEmoji;
function randEmoji() {
var emojiList = [";)", ":D"];
var emoji = emojiList[Math.floor(Math.random() * emojiList.length)];
if (oldEmoji == emoji) {
randEmoji();
} else {
console.log(emoji);
oldEmoji = emoji;
}
}
randEmoji();
randEmoji();
randEmoji();
randEmoji();
randEmoji();
randEmoji();
randEmoji();
看这里,我们实际上从来没有重复过。
TA贡献2041条经验 获得超4个赞
var oldEmoji = '';
var emoji = '';
var emojiList = [";)", ":D", "xD", ":O", ":X", ":P"];
function randEmoji(){
// remove old emoji first to avoid doing a recursive call
var check = oldEmoji? emojiList.filter(e => e !== oldEmoji ) : emojiList;
var emoji = check[Math.floor(Math.random() * check.length)];
oldEmoji = emoji
document.getElementById("emojiText").innerHTML = "Look how fun! ---> " + emoji + " <--- An emoji!";
console.log(emoji);
}
添加回答
举报