从多维数组中获取随机数

时间:2014-07-29 07:17:24

标签: javascript multidimensional-array

在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] ]

];

2 个答案:

答案 0 :(得分:2)

这可行:

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)))];
}

答案 1 :(得分:0)

这是一个应该起作用的递归函数

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/