这是代码,当我运行它时,它将进入无限循环,代码中的任何缺陷?
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
};
function guid() {
return [s4(), s4(), '-' , s4(), '-', s4(), '-', s4(), '-', s4(), s4(), s4()].join('');
}
function randomFromInterval(from,to){
return Math.floor(Math.random()*(to-from+1)+from);
}
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
var data = new Array(500), types = ["date", "slider", "select", "string", "number", "rating", "level", "title"],
allowModify = [true, false], str = "Cell";
for(var i = 0; i < 500; i++){
var arr = new Array(100);
for(var j = 0; j < 100; j++){
var obj = {};
obj.id = guid();
obj.role = types[randomFromInterval(0, 6)];
obj.selected = "";
obj.writable = allowModify[randomFromInterval(0, 1)];
switch(obj.role){
case "slider":
obj.range = [0, randomFromInterval(0, 100)];
obj.text = 0;
break;
case "select":
var num = randomFromInterval(2, 4), _options = Array(num);
for(var opt = 0; opt < num; opt += 1 ){
_options[opt] = {
id : guid(),
text : ["Option[", opt + 1, "]"].join('')
}
}
obj.options = _options;
obj.selected = _options[randomFromInterval(0, num - 1)];
obj.text = obj.selected.text;
obj.selected = obj.selected.id;
break;
case "date":
obj.text = [randomFromInterval(2000, 2013), randomFromInterval(1, 12), randomFromInterval(1, 25)].join('/');
break;
case "string":
obj.text = [str, "[", i , "][", j, "]"].join('');
break;
case "number":
obj.text = randomFromInterval(1, 176432);
break;
case "rating":
var _arr = [], colors = randomFromInterval(0, num - 1);
for(var i = 0; i < colors; i++){
_arr[i] = get_random_color();
}
obj.colors = _arr;
obj.text = _arr[1];
break;
case "level":
obj.text = randomFromInterval(0, 100);
obj.valid = {
"0-40" : get_random_color(),
"40-50" : get_random_color(),
"50-100" : get_random_color()
}
break;
}
arr[j] = obj;
}
data[i] = arr;
}
console.log(data);
答案 0 :(得分:3)
你在循环中使用i
两次,第一个在外循环中,第二个在循环中使用“rating”,将i
设置为颜色数,我认为不到500。
因此,如果在前几个对象中有一个角色为“rating”的对象,i
将永远不会达到500,从而以无限循环结束。
答案 1 :(得分:2)
你有这个内循环:
for(var i = 0; i < colors; i++){
arr[i] = get_random_color();
}
它重置了i的值,弄乱了外循环。您可以通过在此选择其他名称来解决此问题。