如何阻止我的程序连续两次输出相同的内容?

因此,我创建了这个包含一些 JavaScript 的 HTML 页面。我有这个按钮可以输出六分之一的表情符号。它工作正常,然后我添加了一些代码来阻止程序连续两次输出相同的表情符号,但它没有任何区别,我不知道为什么。

这是我的代码:


function randEmoji()

        {

            var oldEmoji = emoji;

            var emojiList = [";)", ":D", "xD", ":O", ":X", ":P"];

            var emoji = emojiList[Math.floor(Math.random() * emojiList.length)];


            if (oldEmoji == emoji)

            {

                randEmoji();

            }

            else

            {

                document.getElementById("emojiText").innerHTML = "Look how fun! ---> " + emoji + " <--- An emoji!";

                console.log(emoji);

            }

        }

我不太擅长编程,也不知道是什么导致了这个问题。


芜湖不芜
浏览 131回答 3
3回答

精慕HU

您必须在函数外部声明变量并将它们设置在函数内部。否则它们的值在每次函数调用中都会被重置。尝试这个:var oldEmoji = '';var emoji = '';var emojiList = [";)", ":D", "xD", ":O", ":X", ":P"];function randEmoji() {&nbsp; &nbsp; oldEmoji = emoji;&nbsp; &nbsp; emoji = emojiList[Math.floor(Math.random() * emojiList.length)];&nbsp; &nbsp; if (oldEmoji == emoji) {&nbsp; &nbsp; &nbsp; &nbsp; randEmoji();&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; console.log(emoji);&nbsp; &nbsp; }}var i = 0;while (i < 20) {&nbsp; &nbsp; randEmoji();&nbsp; &nbsp; i += 1;}

蓝山帝景

问题在于函数作用域的任何局部变量(意味着在函数内部声明)在函数完成执行后都会被丢弃。因此,每次运行该函数emoji并oldEmoji从undefined一种解决方案是将其中一个声明移动到父范围,如下所示:var oldEmoji;function randEmoji() {&nbsp; &nbsp; var emojiList = [";)", ":D"];&nbsp; &nbsp; var emoji = emojiList[Math.floor(Math.random() * emojiList.length)];&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (oldEmoji == emoji) {&nbsp; &nbsp; &nbsp; &nbsp; randEmoji();&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; console.log(emoji);&nbsp; &nbsp; &nbsp; &nbsp; oldEmoji = emoji;&nbsp; &nbsp; }}randEmoji();randEmoji();randEmoji();randEmoji();randEmoji();randEmoji();randEmoji();看这里,我们实际上从来没有重复过。

缥缈止盈

var oldEmoji = '';&nbsp; &nbsp; &nbsp; var emoji = '';&nbsp; &nbsp; &nbsp; var emojiList = [";)", ":D", "xD", ":O", ":X", ":P"];&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; function randEmoji(){&nbsp; &nbsp; &nbsp; &nbsp;// remove old emoji first to avoid doing a recursive call&nbsp; &nbsp; &nbsp; &nbsp;var check = oldEmoji? emojiList.filter(e => e !== oldEmoji ) :&nbsp; emojiList;&nbsp; &nbsp; &nbsp; &nbsp;var emoji = check[Math.floor(Math.random() * check.length)];&nbsp; &nbsp; &nbsp; &nbsp;oldEmoji = emoji&nbsp; &nbsp; &nbsp; &nbsp;document.getElementById("emojiText").innerHTML = "Look how fun! ---> " + emoji + " <--- An emoji!";&nbsp; &nbsp; &nbsp; &nbsp;console.log(emoji);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript