检查数组中是否有多个值。

时间:2021-11-28 07:42:41

this is super similar to this question: How to check whether multiple values exist within an Javascript array

这与这个问题非常相似:如何检查Javascript数组中是否存在多个值。

basically I need to take an array and say does it contain the following 2 value in no particular order

基本上,我需要一个数组,并说它是否包含以下两个值,没有特定的顺序。

But

I can't use any external libraries like j.query because it's a school assignment. I know you don't want to do my assignment for me i just need this small help to answer a larger question (the only reason I put this paragraph in is because one of my other questions didn't get answers because everyone said: "it's your school work, you do it" thats nice and good but i dont know where to start on this one so yeah...)

我不能使用任何外部库,比如j。因为这是学校的作业。我知道你不想做我的作业我就需要这个小的帮助回答一个更大的问题(我把这一段放在唯一的原因是我的另一个问题没有得到答案,因为每个人都说:“这是你的功课,你“这很不错,但我不知道从哪里开始在这一点所以…)

thanks in advance.

提前谢谢。

Fane

神庙

1 个解决方案

#1


0  

if you need only a function

如果你只需要一个函数。

var arr = [1,2,3,4]

contains(2,4, arr) // true

function contains(a, b, arr){
  return arr.indexOf(a) > -1 && arr.indexOf(b) > -1
}

or you can add a prototype as well

或者你也可以添加一个原型。

Array.prototype.containsTwo = function(a, b){
  return this.indexOf(a) > -1 && this.indexOf(b) > -1
}

[1,2,3].containsTwo(1,3) // true

if you want to check multiple values not just two

如果您想要检查多个值,而不仅仅是两个。

Array.prototype.containsLot = function(){
  arguments.every(function(v){
    return this.indexOf(v) > -1
  })
}

[1,22,33,321,41,4].containsLot(1,33,22,4) // true
[1,22,33,321,41,4].containsLot(1,22,33,9) // false

#1


0  

if you need only a function

如果你只需要一个函数。

var arr = [1,2,3,4]

contains(2,4, arr) // true

function contains(a, b, arr){
  return arr.indexOf(a) > -1 && arr.indexOf(b) > -1
}

or you can add a prototype as well

或者你也可以添加一个原型。

Array.prototype.containsTwo = function(a, b){
  return this.indexOf(a) > -1 && this.indexOf(b) > -1
}

[1,2,3].containsTwo(1,3) // true

if you want to check multiple values not just two

如果您想要检查多个值,而不仅仅是两个。

Array.prototype.containsLot = function(){
  arguments.every(function(v){
    return this.indexOf(v) > -1
  })
}

[1,22,33,321,41,4].containsLot(1,33,22,4) // true
[1,22,33,321,41,4].containsLot(1,22,33,9) // false