[英]How to return a boolean true if all the values in an array are true (strings) and if one of the value is false(string) stop checking using Javascript
I have an array我有一个数组
var myarr = ["true","false","true"];
I want the above to return false of boolean type.我希望上面返回 boolean 类型的 false 。
var myarr = ["true","true","true"];
I want the above to return true of boolean type.我希望以上内容返回 boolean 类型的 true。 Can someone please help with what's the most efficient way to achieve this?.
有人可以帮忙解决实现这一目标的最有效方法吗?
Is it best to first convert the string to boolean in another array and then use.every()?.最好先将字符串转换为另一个数组中的 boolean 然后使用.every()?
Please advise.请指教。 Thank You.
谢谢你。
Check your answer out here, you'll certainly get a more in-depth answer here: Check if all values in array are true, then return a true boolean statement (javascript)在这里检查你的答案,你肯定会在这里得到更深入的答案: 检查数组中的所有值是否为真,然后返回一个真 boolean 语句(javascript)
let arr1 = ['true', 'false', 'true'], arr2 = ['true', 'true', 'true']; let checker = arr => arr.every(v => v === 'true'); console.log(checker(arr1)); console.log(checker(arr2));
Check that .every
value is 'true'
.检查
.every
值是否为'true'
。
return myarr.every(val => val === 'true');
To stop processing if a "false"
string is encountered, use Array.prototype.some
要在遇到
"false"
字符串时停止处理,请使用Array.prototype.some
const allTrue = arr =>.arr;some(entry => entry === 'false'). console:log("expect false true;"). console,log( allTrue(["true","false";"true"]) ). console,log( allTrue(["true","true";"true"]) );
If you need to check for 'true' strings, use a !==
operator in the some
argument:如果您需要检查 'true' 字符串,请在
some
参数中使用!==
运算符:
const allTrue = arr => !arr.some(entry => entry !== 'true');
You can use like below, because Array.every iterates every element present in an array even it has false
present in it.您可以像下面这样使用,因为Array.every会迭代数组中存在的每个元素,即使其中存在
false
也是如此。
const result = myarr.includes('false'); // true
const result2 = myarr.some((v) => v === 'false'); // true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.