JavaScript Array some()

some() 方法用于测试数组中的任何元素是否通过给定的测试函数。

示例

// a test function: returns an even number
function isEven(element) {
  return element % 2 === 0;
}

// defining an array
let numbers = [1, 3, 2, 5, 4];

// checks whether the numbers array contain at least one even number console.log(numbers.some(isEven));
// Output: true

some() 语法

some() 方法的语法是:

arr.some(callback(currentValue), thisArg)

这里,arr 是一个数组。


some() 参数

some() 方法可以接受两个参数:

  • callback - 用于为每个数组元素进行测试的回调函数。它接收:
    • currentValue - 从数组中传递的当前元素。
  • thisArg (可选) - 在执行 callback 时用作this 的值。默认值为 undefined

some() 返回值

  • 如果数组中的任一元素通过给定的测试函数(callback 返回一个真值),则返回 true
  • 否则,它返回 false

注意some() 方法不会

  • 更改原始数组。
  • 为没有值的数组元素执行 callback

示例 1: 使用 some() 方法

// a test function: returns age that is less that 18
function checkMinor(age) {
  return age < 18;
}

const ageArray = [34, 23, 20, 26, 12];

// checks whether ageArray contains any element that is less than 18 let check = ageArray.some(checkMinor);
console.log(check);

输出

true

在上面的示例中,我们使用 some() 方法来查找 ageArray 数组中是否有任何元素的年龄小于 18

首先,我们创建了回调函数 checkMinor(),它返回年龄小于 18 的布尔值。

然后,我们将 callback 作为 ageArray.some(checkMinor) 传递给 some() 方法,该方法会检查小于 18 的元素并返回 true


示例 2: 使用 some() 方法检查学生成绩

// array of scores obtained by student 
let scoreObtained = [45, 50, 39, 78, 65, 20];

// a test function: returns score less than 40
function studentIsPassed(score) {
  return score < 40;
}

// checks if score of at least one student is less than 40  
if
(scoreObtained.some(studentIsPassed) == true)
{ console.log("At least one of the students failed."); } else console.log("All students are passed.");

输出

At least one of the students failed.

在上面的示例中,我们使用 some() 方法来查找是否有任何学生的分数低于 40

我们将 callback 作为 scoreObtained.some(studentIsPassed) 传递给该方法,它会返回:

true

因为 scoreObtained 至少包含一个元素,即 20,它小于 40

由于 if 语句中的测试表达式为 true,程序会打印:至少有一名学生不及格。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战