检查数组是否包含“等于"对象 [英] Check if array contains 'equal' object

查看:63
本文介绍了检查数组是否包含“等于"对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is a simplified example, but say I want to generate 5 unique positions on a 100x100 grid. These positions will be stored in an array [[x, y], ...].

尝试了一种显而易见的方法,即生成随机x和y并检查数组[x,y]是否已在结果数组中.如果是,则生成不同的值,如果没有,则将其添加到结果数组中.

The tried the obvious method of generating a random x and y and checking to see if the array [x, y] is already in the result array. If it is, generate different values, if not add it to the result array.

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

但是,由于数组在技术上是不同的对象,因此将永远找不到重复项.那么,检测数组是否包含相等"数组/对象的首选方法是什么?

However, this will never find the duplicates, as the arrays are technically different objects. So, what is the preferred method for detecting if an array contains an 'equal' array/object?

推荐答案

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

You can use some() instead of includes() and use join() before compare

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 .因为两个数组都有不同的引用

You can't compare two arrays by simple equality in js. For example []===[] is false. Because both arrays have difference references

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

这篇关于检查数组是否包含“等于"对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆