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?
- 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");
本文标签: javascriptHow to find a bool value in an arrayStack Overflow
版权声明:本文标题:javascript - How to find a bool value in an array? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744085563a2588453.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论