freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../functional-programming/use-the-every-method-to-che...

1.6 KiB
Raw Blame History

id title challengeType forumTopicId dashedName
587d7dab367417b2b2512b6e 使用 every 方法检查数组中的每个元素是否符合条件 1 301312 use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria

--description--

every方法用于检测数组中所有元素是否都符合指定条件。如果所有元素满足条件,返回布尔值true,反之返回false

举个例子,下面的代码检测数组numbers的所有元素是否都小于 10

var numbers = [1, 5, 8, 0, 10, 11];
numbers.every(function(currentValue) {
  return currentValue < 10;
});
// Returns false

--instructions--

checkPositive函数中使用every方法检查arr中是否所有元素都是正数,函数应返回一个布尔值。

--hints--

应使用every方法。

assert(code.match(/\.every/g));

checkPositive([1, 2, 3, -4, 5])应返回false

assert.isFalse(checkPositive([1, 2, 3, -4, 5]));

checkPositive([1, 2, 3, 4, 5])应返回true

assert.isTrue(checkPositive([1, 2, 3, 4, 5]));

checkPositive([1, -2, 3, -4, 5])应返回false

assert.isFalse(checkPositive([1, -2, 3, -4, 5]));

--seed--

--seed-contents--

function checkPositive(arr) {
  // Only change code below this line


  // Only change code above this line
}
checkPositive([1, 2, 3, -4, 5]);

--solutions--

function checkPositive(arr) {
  // Only change code below this line
  return arr.every(num => num > 0);
  // Only change code above this line
}
checkPositive([1, 2, 3, -4, 5]);