数组中的filter方法_数组filter()方法以及JavaScript中的示例

数组中的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方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值