数组some方法
JavaScript some()方法 (JavaScript some() method)
some() method is used to check a condition on all array elements (or specified elements) and returns true if any of the array elements matches the condition and returns false if all array elements do not match the condition.
一些()方法被用来检查在所有的数组元素(或指定的元素),并返回true的条件,如果任何数组元素的相匹配的条件,并返回假如果所有数组元素不匹配的条件。
Syntax:
句法:
array.some(function, [value]);
Parameters: A function name and an optional value to be tested with all elements.
参数:要与所有元素一起测试的功能名称和可选值 。
Return value: true or false
返回值: true或false
Example:
例:
Input:
var arr1 = [10, 20, -30, -40, -50];
var arr2 = [-10, -1, -20, -40, -50];
//function to check elements are positive or not
function isPositive(n){
return n>=0;
}
Function call:
arr1.some(isPositive);
arr2.some(isPositive)
Output:
true
false
JavaScript Code to check whether any of the array elements is positive or not using Array.every() method
JavaScript代码使用Array.every()方法检查任何数组元素是否为正
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
//function to check positive numbers
function isPositive(n){
return n>=0;
}
var arr1 = [10, 20, -30, -40, -50];
var arr2 = [-10, -1, -20, -40, -50];
if(arr1.some(isPositive)==true)
document.write("arr1 has atleast one positive value<br>");
else
document.write("arr1 does not have any positive value<br>");
if(arr2.some(isPositive)==true)
document.write("arr2 has atleast one positive value<br>");
else
document.write("arr2 does not have any positive value<br>");
</script>
</body>
</html>
Output
输出量
arr1 has atleast one positive value
arr2 does not have any positive value
JavaScript Code to check whether any of the array elements is greater than 10 or not using Array.every() method
JavaScript代码使用Array.every()方法检查任何数组元素是否大于10
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
//function to check positive numbers
function isPositive(n, value2test){
return n>=value2test;
}
var arr1 = [10, 2, 20, 4, 6];
var arr2 = [-1, 2, 3, 4, 9];
if(arr1.every(isPositive, 10)==true)
document.write("arr1 has atleast one element >=10<br>");
else
document.write("arr1 does not have any element >=10<br>");
if(arr2.every(isPositive, 10)==true)
document.write("arr2 has atleast one element >=10<br>");
else
document.write("arr2 does not have any element >=10<br>");
</script>
</body>
</html>
Output
输出量
arr1 has atleast one element >=10
arr2 does not have any element >=10
翻译自: https://www.includehelp.com/code-snippets/array-some-method-with-example-in-javascript.aspx
数组some方法