检查数组中的每个元素是否都有特定值 [英] Check if every element in array has a specfic value

查看:101
本文介绍了检查数组中的每个元素是否都有特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含整数的数组;和一个返回字符串的函数.在此示例中,该函数根据是否执行过特定任务这一事实,返回'solved''unsolved'.

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', based on the fact if a specific task was done before or not.

现在,我需要一种以每个数组元素作为参数调用我的函数,并检查函数是否为每个元素返回'solved'的方法.

Now I need a way to call my function with every array element as parameter and check if the function returns 'solved' for every element.

带有实际值的小例子:

var array1 = [2,5,8]; // 2 is solved, 5 is solved, 8 is unsolved
var array2 = [2,5,6]; // every element is solved

if (Function returns solved for every element) {
// array2 would be accepted for this part
}
else {
// array1 would go in this branch
}

推荐答案

Array.prototype.every()

every()方法测试数组中的所有元素是否通过提供的功能实现的测试.

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

如果您已经有一个返回字符串的函数( ie 'solved''unsolved'),则可以在提供给.every()的回调中将其简单地转换为布尔值.

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

这篇关于检查数组中的每个元素是否都有特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆