如何获得在JavaScript两个数组的子集? [英] How to get subset of two arrays in javascript?

查看:495
本文介绍了如何获得在JavaScript两个数组的子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所试图做的是,如果我有阵
A = {1,2,3,4};
B = {1,2};

What I am trying to do is if I have Array a = {1,2,3,4}; b = {1,2};

然后我想子阵列的 C = {3,4};

任何人可以帮助我吗?

推荐答案

我不知道任何内置的方式做到这一点,你基本上是通过必须循环ç,并检查每个元素是否在 A ,如果是这样,将其删除。该 阵列#的indexOf 方法可以帮你检查,但并非所有的实现有它(尽管大多数做)。去除可通过 阵列#接续

I'm not aware of any built-in way to do this, you basically have to loop through c and check whether each element is in a and, if so, remove it. The Array#indexOf method can help you with checking, but not all implementations have it (though most do). Removal can be via Array#splice.

所以:

var a, c, index;
a = [1, 2];
c = [1, 2, 3, 4];
for (index = c.length - 1; index >= 0; --index) {
    if (a.indexOf(c[index]) >= 0) {
        c.splice(index, 1);
    }
}

...,然后或者提供你自己的实施阵列#的indexOf 如果您的环境不支持,或者使用类似的供给为你(jQuery的给它给你一样好,但通过自身的http://api.jquery.com /jQuery.inArray/相对=nofollow> jQuery.inArray 功能)。如果自己做吧:

...and then either supply your own implementation of Array#indexOf if your environment doesn't support it, or use a library like Prototype that supplies it for you (jQuery gives it to you as well, but through its own jQuery.inArray function). If doing it yourself:

if (!Array.prototype.indexOf) {
  (function() {
    Array.prototype.indexOf = Array_indexOf;
    function Array_indexOf(elm) {
      var index;
      for (index = 0; index < this.length; ++index) {
        if (this[index] === elm) {
          return index;
        }
      }
      return -1;
    }
  })();
}

请注意,当与写得不好code code完成添加到阵列原型如上可能是危险的使得对环境的假设。具体来说,code,它把的for..in ,就像它遍历数组元素的索引(不,它看起来通过的对象属性名阵列原型EM>)会搞的一团糟。 (这可能是为什么jQuery的没有做到这一点。)

Note that adding to the Array prototype as above can be dangerous when done with poorly-written code code that makes assumptions about the environment. Specifically, code that treats for..in as though it loops through array element indexes (it doesn't, it looks through object property names) will get messed up if you add to the Array prototype. (That's probably why jQuery doesn't do it.)

活生生的例子

这篇关于如何获得在JavaScript两个数组的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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