admin管理员组

文章数量:1395248

I have a bool array.

var arr = [true, false, true,false, true]

My requirement:

If the array contains a bool value true I want to show a single alert 'array contains a true value'. Alert should not be multiple. Can someone suggest how to achieve it in javascript?

I have a bool array.

var arr = [true, false, true,false, true]

My requirement:

If the array contains a bool value true I want to show a single alert 'array contains a true value'. Alert should not be multiple. Can someone suggest how to achieve it in javascript?

Share Improve this question edited Feb 5, 2018 at 6:11 D-Shih 46.3k6 gold badges36 silver badges55 bronze badges asked Feb 5, 2018 at 5:01 Soumya BeheraSoumya Behera 2,5225 gold badges17 silver badges25 bronze badges 2
  • 2 Possible duplicate of How do I check if an array includes an object in JavaScript? – Rajesh Commented Feb 5, 2018 at 5:07
  • Soumya, Please note that SO is not get code for free site. You have to try first and if you end up with some problem, share the problem with your attempt and we will help you. – Rajesh Commented Feb 5, 2018 at 5:14
Add a ment  | 

4 Answers 4

Reset to default 5

includes will do

var arr = [true, false, true,false, true]
if(arr.includes(true)){
alert("true found");
}

you can use Array.prototype.some for this purpose also.

var arr = [true, false, true,false, true]
if(arr.some((elem)=> elem === true))
{
 console.log('contains true')
}

You can also use Array.prototype.findIndex method. If not found it will return -1.

if(arr.findIndex(elem=>elem === true)!=-1){
    console.log('contains true')
}

Object.is ( ) uses === internally. So you can use it as well

if(arr.some(elem=>Object.is(elem,true))){
   console.log('contains true')
}

array.prototype.indexOf also uses === internally.

if(arr.indexOf(true) != -1){
   console.log('contains true')
}

There are so many ways to choose from.Pick the one that suits your need.

You could try this:

for(var i=0; i<arr.length; i++){
    if(arr[i]){
        alert("Array contains a true value");
        break;
    }
}

OR

var b = false;
for(var i=0; i<arr.length; i++)
    b = b || arr[i];

if(b) 
    alert("Array contains a true value");

You could simply use Array.prototype.some, Following is the code.

let arr = [true, false, true,false, true]
if(arr.some(e=>e))
  alert("true is included in the array");

本文标签: javascriptHow to find a bool value in an arrayStack Overflow