开发者

javascript: building a conditional off of array items

开发者 https://www.devze.com 2023-02-05 07:23 出处:网络
if I have an array like this: thisarray = new Array(\"this\", \"that\", \"theotherthing\"); how could I go about building a conditional like so:

if I have an array like this:

thisarray = new Array("this", "that", "theotherthing");

how could I go about building a conditional like so:

if(thisarray[0] == thisvar && thisarray[1] == thisvar && thisarray[2] == thisvar) { 
    //do something
}

the caveat is that I do not know how many items could be in thisarray. I'm a bit stum开发者_运维百科ped as to how to accomplish this. Any help would be appreciated.


If you have Javascript 1.6 support, you can do it in one line:

if (thisarray.every(function(e) { return (e == thisvar); })) {
  // Do stuff
}

MDN reference


var valid = true;
for(var i=0; i<thisarray.length && valid; ++i){
    if (thisarray[i] != thisvar)
        valid = false;
}
//use valid
if(valid)
{
    //Do your stuff
}


You can use a for loop to "iterate" through the items in the array, checking the value each time.

var result = true;
for(var x=0; x < thisarray.length; x+=1){
    if(thisarray[x] != thisvar){
       result = false;
    }
}

result will be true if every item of the array equals thisvar, false if there is a mismatch.


You could write a function:

function all(arr, f) {
  for (var i = 0; i < arr.length; ++i)
    if (!f(arr[i], i)) return false;
  return true;
}

Then you can call:

if (all(thisArray, function(a) { return a === thisvar; })) {
  // all equal
}


UPDATE: I mis-read your request to check if any of the elements match, when what you asked for is for all of them to match. I'm leaving my answer here though for reference if you want the condition to be true for any match.

You could just iterate through the elements with a for loop, like this:

for (var i = 0; i < thisarray.length; i++) {
    if (thisarray[i] == thisvar) {
        // do something
        break; // so it doesn't repeat if there are multiple matches
    }
}


Just have an array of actual values and an array of expected values and then compare elements. Something like this:

function arraysEqual(actual, expected) {
  if (actual.length !== expected.length) { return false; }
  var count = actual.length;
  for (i = 0; i < count; i++) {
    if (actual[i] !== expected[i]) { return false; }
  }
  return true;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消