向对象添加唯一数组并确保它们不同

时间:2018-02-19 16:10:37

标签: javascript arrays object

我希望有一个由包含整数的数组组成的对象作为另一个方法使用的指标。每个整数数组必须不同,但我的函数必须随机创建它们,并且在添加新数组时确保它不存在,但同时必须添加特定数量的数组。

假设我想要一个看起来像这样的对象:

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

我在审核position时是否已存在arrayOfPositions时遗漏了一些内容。我尝试了indexOflastIndexOf但是在第一个数组添加后它总是停止。

2 个答案:

答案 0 :(得分:1)

问题是你在搜索对象的索引(在这种情况下是一个数组)时使用indexOflastIndexOf,而且它们都只适用于primitives

您可以stringify值(1)或检查内部数组值是否相等(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]
}

答案 1 :(得分:-1)

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

一个集是唯一的,所以如果你添加相同的值,那么它将被忽略。

如果你想使用像mapfilterreduce这样的数组函数,那么你可以Array.from(positionSet);或者如果你没有ES7,那么你可以写Array.prototype.slice.call(positionSet);