在javascript函数中,我有一个多维数组,如下所示。我怎么能从myObject[1]得到一个随机数?
var myObject= [
[ [2,3], [5,9], [4,7] ],
[ [1,3], [5,8] ],
[ [1,2], [5,7], [6,9] ],
[ [5,6], [1,7] ],
[ [4,6], [1,9], [3,7],[2,8] ],
[ [4,5], [3,9] ],
[ [8,9], [3,5], [1,4] ],
[ [7,9], [2,5] ],
[ [7,8], [1,5], [3,6] ]
,
可以这样做:
var randomNumber = getRandom(myObject[1]);
function getRandom(arr) {
var random1 = Math.floor((Math.random() * (arr.length)));
return arr[random1][Math.floor((Math.random() * (arr[random1].length)))];
}
下面是一个递归函数,它应该可以达到这个目的
var multiDimNumberPicker = function(inputArray){
var randomItem;
//if item is an array
if( Object.prototype.toString.call( inputArray ) === '[object Array]' ) {
//pick a random item to return
randomItem = inputArray[Math.floor(Math.random()*inputArray.length)];
console.log("is still array " + randomItem);
//process selected item
return multiDimNumberPicker(randomItem);
}else{
console.log("not an array " + inputArray);
return inputArray;
}
};
//Generate a random number from myObject[1];
var x = multiDimNumberPicker(myObject[1]);
console.log(x);
//Generate a random number from myObject;
var y = multiDimNumberPicker(myObject);
console.log(y);
示例jsFiddle http://jsfiddle.net/rqk5m/1/