JavaScript 算法未正确过滤



JavaScript的新手。我正在编写一个随机显示报价的程序。问题是,除非使用了整个引号数组,否则我也希望相同的引号永远不会重复。

该程序确实会生成报价,但它们并非每次都是唯一的。这是脚本:

// Random Quote Generator - Justin Duncan
// Create the array of quote objects and name it quotes
var quotes = [{
quote: "I love you the more in that I believe you had" +
" liked me for my own sake and for nothing else.",
source: "John Keats",
categorization: "love",
year: ""
},
{
quote: "But man is not made for defeat. A man can be destroyed but not defeated.",
source: "Ernest Hemingway",
categorization: "philosophy",
year: ""
},
{
quote: "When you reach the end of your rope, tie a knot in it and hang on.",
source: "Franklin D. Roosevelt",
categorization: "motivation",
year: ""
},
{
quote: "There is nothing permanent except change.",
source: "Heraclitus",
categorization: "philosophy",
year: ""
},
{
quote: "You cannot shake hands with a clenched fist",
source: "Indira Gandhi",
categorization: "philosophy",
year: "1971"
},
{
quote: "Learning never exhausts the mind",
source: " Leonardo da Vinci",
categorization: "philosophy",
year: ""
},
{
quote: "There is no charm equal to tenderness of heart.",
source: "Jane Austen",
categorization: "motivation",
year: ""
},
];

//To track quotes that have been shown and remove them from random pool
var shownQuotes = [];
// grabs copy of quotes to manipulate
var notShownQuotes = Object.create(quotes);
// Create the getRandomQuote function and name it getRandomQuote
function getRandomQuote() {
if (shownQuotes.length !== 0) {
//checks if a shown quote is in the notShownQuotes arry and removes it
shownQuotes.forEach(function(shownQuote) {
for (var i = 0; i < notShownQuotes.length; i++) {
if (shownQuote.quote == notShownQuotes[i].quote) {
notShownQuotes.splice(i, 1);
}
}
})
}
//resets the array if all have been shown
if (notShownQuotes.length === 0) {
notShownQuotes = Object.create(quotes);
}
// generates random number according to array length
var returnVal = Math.round(Math.random() * notShownQuotes.length - 1);
// in case returnval is an invalid number because of small array size
if (returnVal <= 0) {
return notShownQuotes[0];
} else {
return notShownQuotes[returnVal]
}
}
// Create the printQuote funtion and name it printQuote
function printQuote() {
var tempQuote = getRandomQuote();
var str = '<p class="quote">' +
` ${tempQuote.quote}.</p>` +
`<p class="source">${tempQuote.source}`;
if (tempQuote.year.length !== 0) {
str +=
`<span class="year">${tempQuote.year}</span></p>`
} else {
str += '</p>'
}
//this portion prints to the document
document.getElementById('quote-box').innerHTML = str;
//change background color
document.body.style.backgroundColor = ran3Color();
//change button as well :)
document.getElementById('loadQuote').style.backgroundColor = ran3Color();
//clears timer
clearInterval(timer);
// resets timer
timer = setInterval(printQuote, 5000);
}
//random color generator
function ran3Color() {
var r = Math.round(Math.random() * 360);
var g = Math.round(Math.random() * 360);
var b = Math.round(Math.random() * 360);
return `rgb(${r},${g},${b})`;
}
//set interval for timer
var timer = setInterval(printQuote, 50);
// This event listener will respond to "Show another quote" button clicks
// when user clicks anywhere on the button, the "printQuote" function is called
document.getElementById('loadQuote').addEventListener("click", printQuote, false);

我希望这是一件小事。这不是家庭作业,我想确保我了解如何操作 Js,我显然在这里做错了什么。提前谢谢。

编辑:添加了整个应用程序.js以防这有助于了解我所做的事情和我正在看的方向。

你的代码有 2 个问题

1-当您删除数组的一件时,减少计数器

notShownQuotes.splice(i, 1);
i --;

2-每次显示项目时更新notShownQuotes数组

if (returnVal <= 0) {
notShownQuotes.splice(0, 1);
return notShownQuotes[0];
} else {
notShownQuotes.splice(returnVal, 1);
return notShownQuotes[returnVal];
}

完整代码将是

// Random Quote Generator - Justin Duncan
// Create the array of quote objects and name it quotes
var quotes = [{
quote: "I love you the more in that I believe you had" + " liked me for my own sake and for nothing else.",
source: "John Keats",
categorization: "love",
year: ""
}, {
quote: "But man is not made for defeat. A man can be destroyed but not defeated.",
source: "Ernest Hemingway",
categorization: "philosophy",
year: ""
}, {
quote: "When you reach the end of your rope, tie a knot in it and hang on.",
source: "Franklin D. Roosevelt",
categorization: "motivation",
year: ""
}, {
quote: "There is nothing permanent except change.",
source: "Heraclitus",
categorization: "philosophy",
year: ""
}, {
quote: "You cannot shake hands with a clenched fist",
source: "Indira Gandhi",
categorization: "philosophy",
year: "1971"
}, {
quote: "Learning never exhausts the mind",
source: " Leonardo da Vinci",
categorization: "philosophy",
year: ""
}, {
quote: "There is no charm equal to tenderness of heart.",
source: "Jane Austen",
categorization: "motivation",
year: ""
}, ];
//To track quotes that have been shown and remove them from random pool
var shownQuotes = [];
// grabs copy of quotes to manipulate
var notShownQuotes = Object.create(quotes);
// Create the getRandomQuote function and name it getRandomQuote
function getRandomQuote() {
if (shownQuotes.length !== 0) {
console.log(shownQuotes)
console.log(notShownQuotes)
//checks if a shown quote is in the notShownQuotes arry and removes it
shownQuotes.forEach(function(shownQuote) {
for (var i = 0; i < notShownQuotes.length; i++) {
if (shownQuote.quote == notShownQuotes[i].quote) {
notShownQuotes.splice(i, 1);
i--;
}
}
});
}
//resets the array if all have been shown
if (notShownQuotes.length === 0) {
notShownQuotes = Object.create(quotes);
}
// generates random number according to array length
var returnVal = Math.round(Math.random() * notShownQuotes.length - 1);
// in case returnval is an invalid number because of small array size
if (returnVal <= 0) {
notShownQuotes.splice(0, 1);
return notShownQuotes[0];
} else {
notShownQuotes.splice(returnVal, 1);
return notShownQuotes[returnVal];
}
}
// Create the printQuote funtion and name it printQuote
function printQuote() {
var tempQuote = getRandomQuote();
var str =
'<p class="quote">' +
` ${tempQuote.quote}.</p>` +
`<p class="source">${tempQuote.source}`;
if (tempQuote.year.length !== 0) {
str += `<span class="year">${tempQuote.year}</span></p>`;
} else {
str += "</p>";
}
//this portion prints to the document
document.getElementById("quote-box").innerHTML = str;
//change background color
document.body.style.backgroundColor = ran3Color();
//change button as well :)
document.getElementById("loadQuote").style.backgroundColor = ran3Color();
//clears timer
clearInterval(timer);
// resets timer
timer = setInterval(printQuote, 5000);
}
//random color generator
function ran3Color() {
var r = Math.round(Math.random() * 360);
var g = Math.round(Math.random() * 360);
var b = Math.round(Math.random() * 360);
return `rgb(${r},${g},${b})`;
}
//set interval for timer
var timer = setInterval(printQuote, 50);
// This event listener will respond to "Show another quote" button clicks
// when user clicks anywhere on the button, the "printQuote" function is called
document
.getElementById("loadQuote")
.addEventListener("click", printQuote, false);
<button id="loadQuote">click</button>
<p id="quote-box"></p>

另一种解决方案是:存储只是显示报价,毕竟再次为空数组

// Random Quote Generator - Justin Duncan
// Create the array of quote objects and name it quotes
var quotes = [{
quote: "I love you the more in that I believe you had" + " liked me for my own sake and for nothing else.",
source: "John Keats",
categorization: "love",
year: ""
}, {
quote: "But man is not made for defeat. A man can be destroyed but not defeated.",
source: "Ernest Hemingway",
categorization: "philosophy",
year: ""
}, {
quote: "When you reach the end of your rope, tie a knot in it and hang on.",
source: "Franklin D. Roosevelt",
categorization: "motivation",
year: ""
}, {
quote: "There is nothing permanent except change.",
source: "Heraclitus",
categorization: "philosophy",
year: ""
}, {
quote: "You cannot shake hands with a clenched fist",
source: "Indira Gandhi",
categorization: "philosophy",
year: "1971"
}, {
quote: "Learning never exhausts the mind",
source: " Leonardo da Vinci",
categorization: "philosophy",
year: ""
}, {
quote: "There is no charm equal to tenderness of heart.",
source: "Jane Austen",
categorization: "motivation",
year: ""
}, ];
//To track quotes that have been shown and remove them from random pool
var shownQuotes = [];
// Create the getRandomQuote function and name it getRandomQuote
function getRandomQuote() {
if (shownQuotes.length == quotes.length) {
shownQuotes = [];
}
// generates random number according to array length
var returnVal = Math.floor(Math.random() * quotes.length - 1) + 1;
// in case returnval is an invalid number because of small array size
while (shownQuotes.indexOf(returnVal) != -1) {
returnVal = Math.floor(Math.random() * quotes.length - 1) + 1;
}
if (returnVal <= 0) {
shownQuotes.push(0)
return quotes[0];
} else {
shownQuotes.push(returnVal)
return quotes[returnVal];
}
}
// Create the printQuote funtion and name it printQuote
function printQuote() {
var tempQuote = getRandomQuote();
var str =
'<p class="quote">' +
` ${tempQuote.quote}.</p>` +
`<p class="source">${tempQuote.source}`;
if (tempQuote.year.length !== 0) {
str += `<span class="year">${tempQuote.year}</span></p>`;
} else {
str += "</p>";
}
//this portion prints to the document
document.getElementById("quote-box").innerHTML = str;
//change background color
document.body.style.backgroundColor = ran3Color();
//change button as well :)
document.getElementById("loadQuote").style.backgroundColor = ran3Color();
//clears timer
clearInterval(timer);
// resets timer
timer = setInterval(printQuote, 5000);
}
//random color generator
function ran3Color() {
var r = Math.round(Math.random() * 360);
var g = Math.round(Math.random() * 360);
var b = Math.round(Math.random() * 360);
return `rgb(${r},${g},${b})`;
}
//set interval for timer
var timer = setInterval(printQuote, 50);
// This event listener will respond to "Show another quote" button clicks
// when user clicks anywhere on the button, the "printQuote" function is called
document
.getElementById("loadQuote")
.addEventListener("click", printQuote, false);
<button id="loadQuote">click</button>
<p id="quote-box"></p>

我认为forEach然后splice创建新数组的部分有点令人困惑。您可以使用简单的Array.filter来摆脱已使用的引号,例如:

let shownQuotes = [];
function getRandomQuote () {
// if all quotes were used reset shownQuotes so all quotes can be shown again
if (shownQuotes.length === quotes.length) {
shownQuotes = [];
}
// filter all quotes that have been used
const unusedQuotes = quotes.filter(quote => !shownQuotes.includes(quote));
// get a random index between [0, unusedQuotes.length)
const randomIndex = Math.floor(Math.random() * unusedQuotes.length);
const randomQuote = unusedQuotes[randomIndex];
// add the element to the quotes already shown.
shownQuotes.push(randomQuote);
return randomQuote;
}

我尝试替换您的代码,但我没有输入。 我使用简单的输入。

所以我从中删除了".quote">

if (shownQuote.quote === notShownQuotes[i].quote) {

然后你有一个错误:

我认为您尝试拼接数组以删除重复的对象。 在"for"中使用"splice"时要小心,你一定不要使用"i++",必须使用"i--"!如果您使用"i++",也许在拼接跳过一个对象并且不进行比较之后!看看我的示例输入中的"3"会发生什么。

请运行以下脚本。 比较输出并查看最后的代码(更改的代码(可能会对您有所帮助。

注释:第一个代码不起作用并重置,因为输入没有"引号">

如果选中,则在上部(未定义 === 未定义(

您的代码:

console.log('Your code:')
var notShownQuotes = [1,2,3,3,4,5,4,6], shownQuotes = [1,2,3,6], quotes = [1,2,3,4,6];
function getRandomQuote() {
if (shownQuotes.length !== 0) {
//checks if a shown quote is in the notShownQuotes arry and removes it
shownQuotes.forEach(function(shownQuote) {
for (var i = 0; i < notShownQuotes.length; i++) {
if (shownQuote.quote === notShownQuotes[i].quote) {
			notShownQuotes.splice(i, 1);
			console.log('remove ' + shownQuote);
}
}
})
}
//resets the array if all have been shown
if (notShownQuotes.length === 0) {
notShownQuotes = quotes;
	console.log('reseted');
}
// generates random number according to array length
var returnVal = Math.round(Math.random() * notShownQuotes.length - 1);
// in case returnval is an invalid number because of small array size
if (returnVal <= 0) {
return notShownQuotes[0];
} else {
return notShownQuotes[returnVal]
}
}
console.log('getRandomQuote: ' + getRandomQuote());

您的代码没有".quote":

console.log('Your code Without ".quote"s:')
var notShownQuotes = [1,2,3,3,4,5,4,6], shownQuotes = [1,2,3,6], quotes = [1,2,3,4,6];
function getRandomQuote2() {
if (shownQuotes.length !== 0) {
//checks if a shown quote is in the notShownQuotes arry and removes it
shownQuotes.forEach(function(shownQuote) {
for (var i = 0; i < notShownQuotes.length; i++) {
if (shownQuote === notShownQuotes[i]) {
			notShownQuotes.splice(i, 1);
			console.log('remove ' + shownQuote);
}
}
})
}
//resets the array if all have been shown
if (notShownQuotes.length === 0) {
notShownQuotes = quotes;
	console.log('reseted');
}
// generates random number according to array length
var returnVal = Math.round(Math.random() * notShownQuotes.length - 1);
// in case returnval is an invalid number because of small array size
if (returnVal <= 0) {
return notShownQuotes[0];
} else {
return notShownQuotes[returnVal]
}
}
console.log('getRandomQuote: ' + getRandomQuote2());

更改的代码:####

console.log('Changed code: #####################')
var notShownQuotes = [1,2,3,3,4,5,4,6], shownQuotes = [1,2,3,6], quotes = [1,2,3,4,6];
function getRandomQuote3() {
if (shownQuotes.length !== 0) {
//checks if a shown quote is in the notShownQuotes arry and removes it
shownQuotes.forEach(function(shownQuote) {
for (var i = notShownQuotes.length - 1; i >= 0; i--) {
if (shownQuote === notShownQuotes[i]) {
			notShownQuotes.splice(i, 1);
			console.log('remove ' + shownQuote);
}
}
})
}
//resets the array if all have been shown
if (notShownQuotes.length === 0) {
notShownQuotes = quotes;
	console.log('reseted');
}
// generates random number according to array length
var returnVal = Math.round(Math.random() * notShownQuotes.length - 1);
// in case returnval is an invalid number because of small array size
if (returnVal <= 0) {
return notShownQuotes[0];
} else {
return notShownQuotes[returnVal]
}
}
console.log('getRandomQuote: ' + getRandomQuote3());

最后。 对不起,我的英语:)不好

TRY

var temp_qoute="";
function getRandomQuote() {
if (shownQuotes.length !== 0) {
//checks if a shown quote is in the notShownQuotes arry and removes it
shownQuotes.forEach(function(shownQuote) {
for (var i = 0; i < notShownQuotes.length; i++) {
if (shownQuote.quote === notShownQuotes[i].quote && notShownQuotes[i].quote!=temp_qoute) {
temp_qoute= notShownQuotes[i].quote
notShownQuotes.splice(i, 1);
}
}
})
}
//resets the array if all have been shown
if (notShownQuotes.length === 0) {
notShownQuotes = quotes;
}
// generates random number according to array length
var returnVal = Math.round(Math.random() * notShownQuotes.length - 1);
// in case returnval is an invalid number because of small array size
if (returnVal <= 0) {
return notShownQuotes[0];
} else {
return notShownQuotes[returnVal]
}
}

最新更新