数组中的filter方法
JavaScript filter()方法 (JavaScript filter() method)
filter() method is used to returns an array with the values which pass the given test (condition).
filter()方法用于返回具有通过给定测试(条件)的值的数组。
Syntax:
句法:
array.filter(function, [value]);
Parameters: A function name and an optional value to be tested with all elements.
参数:要与所有元素一起测试的功能名称和可选值 。
Ref: JS Array filter() function
参考: JS Array filter()函数
Return value: An array with the values which pass the test (match the condition)
返回值:具有通过测试(符合条件)的值的数组
Example:
例:
Input:
var numbers = [10, -10, 20, -20, 30, -30, 0, -1];
//function to check positive numbers
function isPositive(n){
return n>=0;
}
//function to check negative numbers
function isNegative(n){
return n<0;
}
Function call:
var positive_numbers = numbers.filter(isPositive);
var negative_numbers = numbers.filter(isNegative);
Output:
positive_numbers: 10,20,30,0
negative_numbers: -10,-20,-30,-1
JavaScript code to create arrays of positive and negative numbers from an array using Array.filter() method
JavaScript代码使用Array.filter()方法从数组创建正负数数组
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
//function to check positive numbers
function isPositive(n){
return n>=0;
}
//function to check negative numbers
function isNegative(n){
return n<0;
}
var numbers = [10, -10, 20, -20, 30, -30, 0, -1];
var positive_numbers = numbers.filter(isPositive);
var negative_numbers = numbers.filter(isNegative);
//printing arrays
document.write("numbers: " + numbers + "<br>");
document.write("positive_numbers: " + positive_numbers + "<br>");
document.write("negative_numbers: " + negative_numbers + "<br>");
</script>
</body>
</html>
Output
输出量
numbers: 10,-10,20,-20,30,-30,0,-1
positive_numbers: 10,20,30,0
negative_numbers: -10,-20,-30,-1
翻译自: https://www.includehelp.com/code-snippets/array-filter-method-with-example-in-javascript.aspx
数组中的filter方法