javascript - How to find a bool value in an array? - Stack Overflow

I have a bool array.var arr = [true, false, true,false, true]My requirement:If the array contains a boo

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");

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744085564a4556107.html

相关推荐

  • javascript - How to find a bool value in an array? - Stack Overflow

    I have a bool array.var arr = [true, false, true,false, true]My requirement:If the array contains a boo

    9天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信