简体   繁体   中英

Return false if one element of array is not empty without use Iterators - Typescript

I have a method where I receive an string array and I want to return false if one of array elements is false.

 myMethod(attrs: Array<String>) {
   for (const element of attrs) {
      if (!element) {
        return false;
      }
    }

    return true;
}

Is it possible to simplify this code?

Try This:

 var attrs =[true,true,false]; var result = !attrs.some( elm => (elm === false) ); console.log(result); 

Javascript Array has a method that checks if every item satisfies a predicate: every .

Example:

const arr = [1, 2, null];

const every = arr.every(item => item !== null); // Check if every item is not-null. This will be false

It can be shortened by casting an item to a boolean:

const every2 = arr.every(item => Boolean(item)); // This will give false for 0, null, undefined, etc.

And even shorter by just passing a Boolean constructor to a callback, which will pass items to it's constructor

const every2 = arr.every(Boolean);

Also check methods find and some .

Keep in mind this does use iterator, it's just that JS built-in functions do it under the hood .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM