javascript
数组中的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 numbersfunction isPositive(n){return n>=0;}//function to check negative numbersfunction 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,0negative_numbers: -10,-20,-30,-1JavaScript 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 numbersfunction isPositive(n){return n>=0;}//function to check negative numbersfunction 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 arraysdocument.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方法
總結
以上是生活随笔為你收集整理的数组中的filter方法_数组filter()方法以及JavaScript中的示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么创建线程池一定要用ThreadPo
- 下一篇: next和hasnext_使用Java中