[英]Add unique arrays to object and make sure they are different
我想要一個由包含整數的數組組成的對象,作為另一個方法使用的指標。 每個整數數組都必須不同,但是我的函數必須隨機創建它們,並在添加新數組時確保它不存在,但同時必須添加特定數量的數組。
可以說我想要一個看起來像這樣的對象:
arr = {
0: [0,0],
1: [0,1],
2: [1,1],
3: [1,0]
}
當然,根據下面Math.random
的隨機方面,上述對象可以采用不同的順序。 那是我的代碼:
let arrayOfPositions = [];
let i = 0;
let position = [];
do {
let randX = Math.round(Math.random());
let randY = Math.round(Math.random());
position = [randX, randY];
arrayOfPositions[i] = position;
i++;
}
while (arrayOfPositions.length < 4 );
有什么東西在我的同時condtition缺少檢查,如果position
在已經存在arrayOfPositions
。 我嘗試了indexOf
和lastIndexOf
但是在添加第一個數組之后它總是停止。
問題是,您在搜索對象(在本例中為數組)的索引時使用indexOf和lastIndexOf ,並且它們兩者都僅適用於圖元 。
您可以對值進行字符串化 (1),也可以檢查內部Array值是否相等(2)。
(1)有點棘手且緩慢,因為您必須將原始數組值( arrayOfPositions
),要添加的新position
都進行字符串化,然后才能使用indexOf
及其派生類。 所以我要跳過那個。
對於(2),我將稍作更改,並假設您可以在使用let
同時使用ES6 Array.find :
let positions = []
do {
const position = createUniquePos(positions)
positions.push(position)
}
while (positions.length < 4)
function createUniquePos(positions) {
const x = Math.round(Math.random())
const y = Math.round(Math.random())
// here we check if that pair already exists in the array
return positions.find( pos => pos[0] === x && pos[1] === y )
// if it does exist, then we do another attempt with recursion
? createUniquePos(positions)
// if it doesn't, then we return the unique position
: [x, y]
}
const positionSet = new Set();
while(positionSet.size < 4){
const randX = Math.round(Math.random());
const randY = Math.round(Math.random());
const position = [randX, randY];
positionSet.add(position);
}
集合是唯一的,因此,如果添加相同的值,則它將被忽略。
如果要使用諸如map
, filter
或reduce
數組函數,則可以執行Array.from(positionSet);
或者,如果沒有ES7,則可以編寫Array.prototype.slice.call(positionSet);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.