gpt4 book ai didi

JavaScript - 随机且不重复 tmp 数组

转载 作者:行者123 更新时间:2023-12-03 07:56:01 25 4
gpt4 key购买 nike

两天以来,我遇到了 JavaScript 中数组和条件的问题。您能否检查我的代码并给我一些建议,我应该纠正什么才能在没有无限循环的情况下运行此代码?

步骤列表(澄清我的问题)-此代码应如何工作:
1. 开始抽奖
2. 获取随机报价 -> quote[r_quote] 其中 r_quote 是随机数 3. 如果tmp数组为空,则将绘制的引号添加到tmp[j]
4. 获取下一个随机报价(第 2 步)
5. 如果tmp不为空
6. 将所有 tmp 元素与新的随机引用进行比较
7. 如果新的随机报价是唯一的,请将其添加到tmp[j]

我目前在第 7 步中遇到问题。当这部分代码取消注释时,循环开始无限处理。

var quote = new Array();
quote[0] = 'AAAAAAAAAA';
quote[1] = 'Lorem ipsum.';
quote[2] = 'BBBBBBBBBB';
quote[3] = 'CCCCCCCCCC';

var numberOfQoutes = quote.length;
var r_quote;

var tmp = new Array();
var j = 0;

console.log("start... ");
for (i = 0; i < 3; i++) {
r_quote = Math.floor(numberOfQoutes * Math.random());
console.log('[Step ' + i + '] \t\nquote[' + r_quote + ']' + ' => ' + quote[r_quote]);

if(tmp.length == 0) {
console.log('\ttmp array is empty. You can append ANY quote.');

tmp[j] = quote[r_quote];
console.log('\t\tAppended: ' + tmp[j]);
console.log(j); // show current tmp array position
j++;
} else {
// add just unique qoute
console.log('\ttmp array is not empty.');
console.log('\tChecking if drawn quotation has already been appended.')

for(k = 0; k < tmp.length; k++) {
console.log("\tk=" + k + "\t" + tmp[k] + "\t<< comparing >>\t" + quote[r_quote]);

if(tmp[k] !== quote[r_quote]) { // this if probably doesn't work
console.log("\t\t[OK] You can append quote.");
console.log(j); // show current tmp array position
console.log('\t\tAssign this quote[' + r_quote + '] => ' + quote[r_quote]);
console.log('\t\tInto tmp[' + j + ']');

/* what's wrong here?
tmp[j] = quote[r_quote]; // I want to add random qoute to new position in array
console.log("Appended: " + tmp[j]);
console.log(k);
j++;
*/
}
}
}
}

最佳答案

问题在于:

for(k = 0; k < tmp.length; k++) {

你检查 k < tmp.length 是否成立,这里:

tmp[j] = quote[r_quote];
j++;

你总是向数组添加另一个元素,因此它的长度不断攀升,直到内存耗尽

关于JavaScript - 随机且不重复 tmp 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34799468/

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