【问题标题】:Check if array contains 'equal' object [duplicate]检查数组是否包含“相等”对象[重复]
【发布时间】:2019-08-24 05:26:43
【问题描述】:

这是一个简化的示例,但假设我想在 100x100 网格上生成 5 个唯一位置。这些位置将存储在数组 [[x, y], ...] 中。

尝试了生成随机 x 和 y 并检查数组 [x, y] 是否已经在结果数组中的明显方法。如果是,则生成不同的值,如果不是,则将其添加到结果数组中。

result = [];
while (result.length !== 5) {
    let x = Math.floor(Math.random() * 100) + 1;
    let y = Math.floor(Math.random() * 100) + 1;
    if (!result.includes([x, y])) {
        result.push(array);
    }
}

但是,这永远不会找到重复项,因为数组在技术上是不同的对象。那么,检测数组是否包含“相等”数组/对象的首选方法是什么?

【问题讨论】:

标签: javascript arrays


【解决方案1】:

您可以使用some() 代替includes() 并在比较之前使用join()

while (result.length !== 5) {
    let x = Math.floor(Math.random() * 10) + 1;
    let y = Math.floor(Math.random() * 10) + 1;
    if (!result.some(i => i.join() === [x, y].join())) {
        result.push(array);
    }
}

你不能在 js 中通过简单的相等来比较两个数组。例如[]===[]false。因为两个数组都有不同的引用

console.log([] === []); //false

includes()也是如此

let pts = [[1,2],[5,6]];

console.log(pts.includes([1,2])); //false

console.log(pts.some(x => [1,2].join() === x.join())); //true

【讨论】:

  • 这在这里有效,因为所有值都是个位数,但最好使用分隔符进行连接,这样可以区分 [11, 2][1, 12] 这样的对,如果矩阵可能更大。
  • 应该在帖子中说明,我需要它来处理多个数字。将编辑帖子。
  • 您可以像这样忽略分隔符参数:.join()。这将默认添加一个,
  • @adiga 感谢您提供信息。我真的忘记了。
  • .toString() 也可以
【解决方案2】:

您可以将Array.some()destructuring 结合使用:

示例:

let arr = [[1,2],[3,4]];

console.log(arr.some(([x, y]) => x === 3 && y === 4));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

因此,您的示例可以改写为:

let result = [];

while (result.length !== 5)
{
    let x = Math.floor(Math.random() * 10) + 1;
    let y = Math.floor(Math.random() * 10) + 1;

    if (!result.some(([a, b]) => a === x && b === y))
    {
        result.push([x, y]);
    }
    else
    {
        console.log(`${[x,y]} is already on the array!`);
    }
}

console.log(JSON.stringify(result));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

【讨论】:

    猜你喜欢
    • 2020-11-29
    • 1970-01-01
    • 2020-06-07
    • 2019-01-12
    • 2018-07-16
    • 2020-08-09
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    相关资源
    最近更新 更多