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?
- 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
4 Answers
Reset to default 5includes 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
评论列表(0条)