最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can you return a Boolean value in loop in this condition - Stack Overflow

programmeradmin1浏览0评论

I hope someone can answer this for me. Is there a way in JavaScript that we can use a loop with an "if" statement inside and only return true if all the values in the loop iterations meet that condition. Thank you

I hope someone can answer this for me. Is there a way in JavaScript that we can use a loop with an "if" statement inside and only return true if all the values in the loop iterations meet that condition. Thank you

Share Improve this question asked Dec 14, 2019 at 15:12 Zaeem Jalil MalikZaeem Jalil Malik 311 silver badge3 bronze badges 1
  • for (…) { if (!condition) return false; } return true – Bergi Commented Dec 14, 2019 at 15:23
Add a ment  | 

2 Answers 2

Reset to default 6

Yes there is. For example the .every method of an Array does this exact thing.
Quoted from MDN:

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

const ages = [24, 32, 22, 21, 29];
const legalDrinkingAge = 21;
const areLegalDrinkingAges = ages.every(age => age >= legalDrinkingAge);

console.log(areLegalDrinkingAges);

You can define a var, e.g. result holding the value true, then executing the for loop and checking the condition using the if statement. Once condition fails, set result to false and break out of the for loop.

At the end, result will be true if the if statement was true for all elements checked and false otherwise.

var result = true;
var a = [12,14,16,18,5,11,12];   // array with example values
for (var i = 0; i < a.length; i ++) {
    if (!(a[i] >= 10)) {  // the condition
        result = false;
        break;
    }
}
console.log(result); // false
发布评论

评论列表(0)

  1. 暂无评论