JavaScript - 数组 some() 方法
在 JavaScript 中,Array.some() 方法接受一个回调函数,并验证数组中是否至少有一个元素通过了回调函数提供的测试。如果至少有一个元素通过测试,则返回"true"。如果函数对所有数组元素都返回 false,则返回"false"。
some() 方法不会对空数组元素执行该函数。它不会更改原始数组;它只会检查元素是否符合指定的条件。
语法
以下是 JavaScript Array.some() 方法的语法 -
some(callbackFn, thisArg)
参数
此方法接受两个参数。如下所述 -
-
callbackFn - 将为数组中的每个元素调用的函数。此函数最多可接收三个参数:
- currentValue − 数组中当前正在处理的元素。
- index(可选)− 数组中当前正在处理的元素的索引。
- array(可选)− 调用 some() 的数组。
- thisArg(可选)− 执行回调函数时用作 this 的值。
返回值
此方法返回一个布尔值作为结果。
示例
示例 1
在下面的示例中,我们使用 JavaScript Array.some() 方法检查提供的数组元素中是否至少有一个正数。
<html>
<body>
<script>
let numbers = [2, 4, -1, 6, 8];
let isPositive = numbers.some(function(num) {
return num > 0;
});
document.write(isPositive);
</script>
</body>
</html>
执行上述程序后,some() 方法返回"true",因为 numbers 数组中至少有一个元素 (2) 为正数。
输出
true
示例 2
在此示例中,我们检查至少一个长度为"5"的字符串元素。
<html>
<body>
<script>
let words = ["apple", "banana", "cherry", "date"];
let isLengthFive = words.some(function(word) {
return word.length === 5;
});
document.write(isLengthFive);
</script>
</body>
</html>
执行上述程序后,some() 方法返回"true",因为数组中至少有一个元素(橙色)的长度为 5。
输出
true
示例 3
如果数组中至少有一个元素满足所提供函数实现的条件,则 some() 方法返回"false"。
<html>
<body>
<script>
let numbers = [1, 3, 5, 9, 7];
let isEven = numbers.some(function(num) {
return num % 2 === 0;
});
document.write(isEven);
</script>
</body>
</html>
输出
false
示例 4
在下面的示例中,我们检查数组中是否存在某个特定元素。
<html>
<body>
<script>
const fruits = ["apple", "banana", "cherry", "mango"];
function exists(arr, val) {
return arr.some((arrVal) => val === arrVal);
}
document.write(exists(fruits, "orange"), "<br>");
document.write(exists(fruits, "banana"));
</script>
</body>
</html>
输出
false true

