Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Javascript生成不同的数字_Javascript - Fatal编程技术网

使用Javascript生成不同的数字

使用Javascript生成不同的数字,javascript,Javascript,我就是这样生成6个不同的数字的: window.random_row = Math.floor(Math.random() * (len_board - 1)) + 1; window.random_column = Math.floor(Math.random() * (len_board - 1)) + 1; window.random_row2 = Math.floor(Math.random() * ((len_board-1) - 1)) + 1; window.random_colu

我就是这样生成6个不同的数字的:

window.random_row = Math.floor(Math.random() * (len_board - 1)) + 1;
window.random_column = Math.floor(Math.random() * (len_board - 1)) + 1;
window.random_row2 = Math.floor(Math.random() * ((len_board-1) - 1)) + 1;
window.random_column2 = Math.floor(Math.random() * ((len_board-1) - 1)) + 1;
window.random_row3 = Math.floor(Math.random() * ((len_board+1) - 1)) + 1;
window.random_column3 = Math.floor(Math.random() * ((len_board+1) - 1)) + 1;

但是,我不希望行/列是相同的数字,例如允许random\u row==random\u column,但我不希望random\u row==random\u row2。我正在考虑使用if/else语句。类似于:if(random_row==random_row2),然后生成一个新的random_row2,但是我想到这个数字可能会再次相同,所以我想这不是正确的方法。有人知道如何解决这个问题吗?

从1.创建一个数字数组。。透镜板 洗牌(使用Math.random()排序<0.5排序函数) 以前6个为例

把它想象成洗一副牌,你不能把同一张牌拖两次


所有这些都是“独一无二的”。

那么,尝试一下while循环怎么样

while(random2 == random1 || random2 == random3) 
{
random2= math.....;
}
我看到了一个很好的答案

根据您的问题:

function generate(qt, len_board) {
    var arr = [];
    while(arr.length < qt) {
        var randomnumber = Math.floor(Math.random() * (len_board - 1)) + 1;
        if(arr.indexOf(randomnumber) > -1) continue;
        arr.push(randomnumber);
    }
    return arr;
} 

var rows=generate(3,len_board);
var columns=generate(3,len_board);

window.random_row = rows[0];
window.random_column = columns[0];
window.random_row2 = rows[1];
window.random_column2 = columns[1];
window.random_row3 = rows[2];
window.random_column3 = columns[2];
函数生成(qt、len_板){
var-arr=[];
while(arr.length-1)继续;
arr.push(随机数);
}
返回arr;
} 
var行=生成(3,len_板);
var列=生成(3,len_板);
window.random_row=行[0];
window.random_column=列[0];
window.random_row2=行[1];
window.random_column2=列[1];
window.random_row3=行[2];
window.random_column3=列[2];