【发布时间】:2021-03-12 20:48:35
【问题描述】:
我在我的网站上研究 Magic 8 ball,不得不在 JS 上编写代码。 一切都很好,直到我决定不让随机答案重复 5 次。 所以基本上,我想要一个包含我得到的最后 5 个结果的数组。
const responses = ["keep up", "no", "dont even think",
"very doubtful", "outlook good", "my sources say no",
"it is decidedly so", "dont count on it", "it is certain",
"ask again later", "reply hazy, try again", "outlook not so good",
"cannot predict now", "better not tell you now", "definetely - yes", "most likely"];
function randomly() {
const random = Math.floor(Math.random() * responses.length);
let result = responses[random];
let lastfive = [];
if (lastfive.includes(result)) {
return randomly();
}
else {
if (lastfive.length = 5) {
lastfive.length = 0;
}
let neew=lastfive.push(result);
console.log("bye:" + lastfive);
return(result);
}
}
})();
【问题讨论】:
-
这个新数组只包含删除旧的最后一个结果。我哪里错了?
-
let lastfive=[];每次调用函数时都会创建一个新数组。
标签: javascript node.js arrays push