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

查看:4995
本文介绍了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() 来检查新生成的坐标集已经包含在改编?我想推入改编如果只坐标是不重复的。

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循环(或同时)来搜索数组中的坐标假设你知道数组的格式(在这种情况下,它是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天全站免登陆