Check if every element in array has a specfic value

前端 未结 1 1887
渐次进展
渐次进展 2021-01-24 06:01

I have an array with integers in it; and a function that returns a string. In this example, the function returns either \'solved\' or \'unsolved\', bas

相关标签:
1条回答
  • 2021-01-24 07:01

    Array.prototype.every()

    The every() method tests whether all elements in the array pass the test implemented by the provided function.

    If you already have a function that returns a string (i.e. 'solved' or 'unsolved'), then you can simply convert that to a boolean inside the callback you supply to .every().

    var array1 = [2, 5, 8]; // 2 is solved, 5 is solved, 8 is unsolved
    var array2 = [2, 5, 6]; // every element is solved
    
    function isSolvedString(operand) {
      return operand < 8 ? 'solved' : 'unsolved';
    }
    
    function isSolved(current) {
      return isSolvedString(current) === 'solved' ? true : false;
    }
    
    console.log(array1.every(isSolved)); // false
    console.log(array2.every(isSolved)); // true

    0 讨论(0)
提交回复
热议问题