![](/img/trans.png)
[英]How to return true if all values of array are true otherwise return false?
[英]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
我有一個數組
var myarr = ["true","false","true"];
我希望上面返回 boolean 類型的 false 。
var myarr = ["true","true","true"];
我希望以上內容返回 boolean 類型的 true。 有人可以幫忙解決實現這一目標的最有效方法嗎?
最好先將字符串轉換為另一個數組中的 boolean 然后使用.every()?
請指教。 謝謝你。
在這里檢查你的答案,你肯定會在這里得到更深入的答案: 檢查數組中的所有值是否為真,然后返回一個真 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));
檢查.every
值是否為'true'
。
return myarr.every(val => val === 'true');
要在遇到"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"]) );
如果您需要檢查 'true' 字符串,請在some
參數中使用!==
運算符:
const allTrue = arr => !arr.some(entry => entry !== 'true');
您可以像下面這樣使用,因為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.