編輯:如果你看過馬特科比的答案,你會看到,它應該工作,但他使用的indexOf()方法和方法不能與IE瀏覽器8或更高版本,我需要它來對IE 8的工作我試着這樣做的工作繞到的indexOf()方法,但它不工作。使用Javascript - 生成隨機數對,如果對不存在
var tester = -1;
for (var test=0; test<xposition.length; test++) {
if (x == xposition[0]) {
tseter = x;
}
}
任何想法爲什麼它不工作?
原題: 所以我要生成隨機數對,但只有當尚未生成數量的對。以下是我的嘗試,希望如果你閱讀我所嘗試的內容,你會明白什麼是我需要的。
function randomPairs() {
var xposition = []; //array which holds all x coordinates
var yposition = []; //array which holds all y coordinates
for (var i=0; i<5; i++) { //do everything below 5 times (generate 5 pairs)
var x = getRandom(1,7); //generate new x point
var y = getRandom(2,7); //generate new y point
if (jQuery.inArray(x, xposition)) { //if newly generated x point is already in the xposition array (if it was already previously generated
var location = xposition.indexOf(x) //find the index of the existing x
if (y == yposition[location]) { //if the newly generated y points equals the same y point in the same location as x, except in the yposition array
while (y == yposition[location]) {
y = getRandom(2, 7); //change y
}
}
}
}
xposition.push(x); //put x into the array
yposition.push(y); //put y into the array
}
那麼,任何想法爲什麼它不工作?我是否正確使用了jQuery.inArray()和.indexOf()方法?
哦,getRandom是
function getRandom(min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
}
基本上,它生成的最小值和最大值之間的一個數。
此外,當我試圖做
alert(xposition);
alert(yposition);
是空白。
你能告訴我們你的'getRandom()'函數嗎?爲什麼x和y的參數不同?你只是通過軸的規模,並做一個'Math.random'?只要確定。 – aug
'function randomPairs(){return [4,4]; }'。直接來自http://xkcd.com/221/ –
'jQuery。inArray(x,xposition)'返回元素的索引如果存在,那麼爲什麼你要在這個函數索引裏搜索? – Dvir