Javascript 二维数组 indexOf [英] Javascript 2d array indexOf

查看:43
本文介绍了Javascript 二维数组 indexOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的二维数组:

I have a 2d array like this:

var arr = [[2,3],[5,8],[1,1],[0,9],[5,7]];

每个索引存储一个内部数组,其中包含某个元素的坐标.

Each index stores an inner array containing the coordinates of some element.

我如何使用 Array.indexOf() 检查新生成的坐标集是否已经包含在 arr 中?如果只有坐标不是重复的,我想推入 arr.

How can I use Array.indexOf() to check if the newly generated set of coordinates is already contained in arr? I want to push into arr if only the coordinate is NOT a duplicate.

这是我没有成功的尝试:

Here is my attempt that didn't work:

if (arr.indexOf([x, y]) == -1) {
    arr.push([x, y]);
}

看起来 indexOf() 不适用于二维数组...

It looks like indexOf() doesn't work for 2d arrays...

推荐答案

你不能使用 indexOf 来处理复杂的数组(除非你将它序列化,使每个坐标都变成字符串),你需要使用 for 循环(或 while)假设您知道数组的格式(在本例中为 2d),则在该数组中搜索该坐标.

You cannot use indexOf to do complicated arrays (unless you serialize it making everything each coordinate into strings), you will need to use a for loop (or while) to search for that coordinate in that array assuming you know the format of the array (in this case it is 2d).

var arr = [[2,3],[5,8],[1,1],[0,9],[5,7]];
var coor1 = [0, 9];
var coor2 = [1, 2];

function isItemInArray(array, item) {
    for (var i = 0; i < array.length; i++) {
        // This if statement depends on the format of your array
        if (array[i][0] == item[0] && array[i][1] == item[1]) {
            return true;   // Found it
        }
    }
    return false;   // Not found
}

// Test coor1
console.log("Is it in there? [0, 9]", isItemInArray(arr, coor1));   // True

// Test coor2
console.log("Is it in there? [1, 2]", isItemInArray(arr, coor2));   // False

// Then
if (!isItemInArray(arr, [x, y])) {
   arr.push([x, y]);
}

这个实现循环并获取每个值.如果你关心性能,你可以做更复杂的事情,比如按第一个索引对原始数组进行排序,然后在第一个索引上使用二分搜索.

This implementation loops and grabs every value. If you care about performance you can do more complicated things like sorting the original array by the first index and then using binary search on the first index.

另一种方法是将数组中每个项目的第一个坐标存储在一个对象(如哈希表)中,并将第二个值存储在每个存储桶中以减少搜索时间;更多信息请访问 http://en.wikipedia.org/wiki/Bucket_sort.

Another way is to bucket the first coordinate of each item in the array in an object (like a hashtable) and bucket the second value in each of those buckets to reduce search times; more info here http://en.wikipedia.org/wiki/Bucket_sort.

否则这可能足以满足您的需要.

Otherwise this is probably good enough for what you need.

这篇关于Javascript 二维数组 indexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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