如何检查是否一个JavaScript数组中存在多个值

编程入门 行业动态 更新时间:2024-10-13 02:19:55
本文介绍了如何检查是否一个JavaScript数组中存在多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以,我使用jQuery,并且都具有多个值,我想检查是否全部第一个数组中的值在第二个存在。

两个数组

有关实例,例如1 ...

  

数组A包含下列值

    

34,78,89

    

数组b中包含以下值

    

78,67,34,99,56,89

    

这将返回真正

...示例2:

  

数组A包含下列值

    

34,78,89

    

数组b中包含以下值

    

78,67,99,56,89

    

这将返回假

...例子3:

  

数组A包含下列值

    

34,78,89

    

数组b中包含以下值

    

78,89

    

这将返回假

到目前为止,我已经试图解决这个:

  • 使用自定义的比较的方法比较两个阵列。问题是,这只是回报真正当阵列是相同的,因为你可以从例如1见我希望它返回true,即使它们不相同,但至少包含值
  • 使用 Jquerys .inArray功能,但对于一个值在数组中此只检查,而不是多个。
  • 这是任何人都可以扔在这的任何光线将是巨大的。

    解决方案

    函数containsAll(针,干草堆){  对于(VAR I = 0,LEN = needles.length; I< LEN,我++){     如果($ inArray(针[I],草垛)== -1)返回false;  }  返回true;}containsAll([34,78,89],[78,67,34,99,56,89]); //真containsAll([34,78,89],[78,67,99,56,89]); //假containsAll([34,78,89],[78,89]); //假

    So, I'm using Jquery and have two arrays both with multiple values and I want to check whether all the values in the first array exist in the second.

    For instance, example 1...

    Array A contains the following values

    34, 78, 89

    Array B contains the following values

    78, 67, 34, 99, 56, 89

    This would return true

    ...example 2:

    Array A contains the following values

    34, 78, 89

    Array B contains the following values

    78, 67, 99, 56, 89

    This would return false

    ...example 3:

    Array A contains the following values

    34, 78, 89

    Array B contains the following values

    78, 89

    This would return false

    So far I have tried to solve this by:

  • Extending Jquery with a custom 'compare' method to compare the two arrays. Problem is this only returns true when the arrays are identical and as you can see from example 1 I want it to return true even if they aren't identical but at least contain the value
  • using Jquerys .inArray function, but this only checks for one value in an array, not multiple.
  • Any light that anyone could throw on this would be great.

    解决方案

    function containsAll(needles, haystack){ for(var i = 0 , len = needles.length; i < len; i++){ if($.inArray(needles[i], haystack) == -1) return false; } return true; } containsAll([34, 78, 89], [78, 67, 34, 99, 56, 89]); // true containsAll([34, 78, 89], [78, 67, 99, 56, 89]); // false containsAll([34, 78, 89], [78, 89]); // false

    更多推荐

    如何检查是否一个JavaScript数组中存在多个值

    本文发布于:2023-11-28 18:28:13,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1643479.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:多个   组中   JavaScript

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!