两天以来我在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++;
*/
}
}
}
}
&#13;
答案 0 :(得分:1)
问题在于:
for(k = 0; k < tmp.length; k++) {
你检查k&lt; tmp.length,这里:
tmp[j] = quote[r_quote];
j++;
你总是在数组中添加另一个元素,所以它的长度会不断攀升,直到你内存不足