简体   繁体   中英

Array inside if conditional in javascript ?

For example:

var array = [1,2,3,4];
if( 5 > array ){
   alert('ok');
}

Can i do this in javascript ?

Can I do this in JavaScript?

I don't know. Try it.

An if statement evaluates a single expression. If you want to evaluate multiple conditions, which is the case here, you have to write the multiple conditions.

if( 5 > array[0] && 5 > array[1] && 5 > array[2] && 5 > array[3]) {
  alert('ok');
}

Since that is not going to work well if you don't know the number of elements in array in advance, you could write a loop, looking for failing cases:

let ok = true;

for (const i = 0; i < array.length; i++) {
  if (5 > array[i]) continue;
  ok = false;
  break;
}

if (ok) alert('ok');

It turns out, though, that arrays have a built-in method to check to see if some condition holds for all elements, so we can write:

if (array.every(elt => 5 > elt)) alert('ok');

Well, it's pretty simple, use .indexOf() ( MDN )

var text ="abc";
var array = ['abc', 'def'];
if(array.indexOf(text) !== -1){
   alert('ok');
}

If you wanted to check if an element(text) exists in the array, then this can be used

if(array.indexOf(text) !== -1){
   alert('ok');
}
var array = [1,2,3,4,5]
var i = 0;
var num = 4;
for(i = 0;i < array.length;i++){
      if(array[i] == num){
            alert("OK")
      }
 }

This can also be used but using the indexOf() function will be much faster

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM