我希望获得一个随机数beetween 0和一个包含对象的数组长度。它几乎正常工作,但我得到的数字有时是“未定义”,我不明白为什么。
这是我的代码:
var temp, stock = [];
var x =
[{'a' :' aa'},{'b ':'qsdf'},{'c':'aaa'},{'d':'ccc'},{'e':'54'},{'f':'l'},
{'a' :' bb'},{'b ':'qsdf'},{'c':'aaa'},{'d':'ccc'},{'e':'54'},{'f':'l'}];
function randomize(min,max) {
return Math.floor((Math.random()*max)+min);
}
function test(tab) {
var tabLength = tab.length;
if(stock.length == tabLength ) {
alert('End')
}else{
temp = randomize(0,tabLength);
if(stock.length == 0) {
stock += temp;
return temp;
}else{
if(stock.indexOf(temp) > -1) {
test(tab);
}else{
stock += temp;
return temp;
}
}
}
}
div.onclick = function () {
var number = test(x)
alert(stock+' '+number)
}