Home >Web Front-end >JS Tutorial >How to return array elements greater than a specified number via js
In the previous article "Calculate the factors of a positive integer using JavaScript" I introduced you how to use JavaScript to calculate the factors of a positive integer. Today I will continue to introduce you to the basic knowledge related to JavaScript~
The main problem description of this article is "How to write a JavaScript function that returns array elements greater than a number"?
What does it mean? For example, there is an array [11, 45, 4, 31, 64, 10]. What should we do if we only need numbers greater than 10?
Very simple!
Let’s go directly to the code:
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title></title> </head> <body> <script> function BiggerElements(val) { return function(evalue, index, array) { return (evalue >= val); }; } var result = [11, 45, 4, 31, 64, 10]. filter(BiggerElements(10)); console.log(result); </script> </body> </html>
The results returned through console.log are as follows: (JavaScript can be written to the browser console by using console.log() "Display" data:)
[11,45,31,64,10]
In the above code, a number I gave is 10, and the original array is [11, 45, 4, 31, 64, 10 ], that is to say, we returned an array element greater than 10 through the customized BiggerElementsh function
Then the javascript function required by the symbol has also been written successfully.
Note:
filter()
method creates a new array. The elements in the new array are checked by checking all elements that meet the conditions in the specified array; filter() Empty arrays are not checked; filter() does not alter the original array. The syntax of the
filter() method is "array.filter(function(currentValue,index,arr), thisValue)
"; the
parameters are as follows :
function(currentValue, index,arr)必须:函数,数组中的每个元素都会执行这个函数 【函数参数: 参数描述currentValue必须:当前元素的值index可选。 当前元素的索引值arr可选:当前元素属于的数组对象】 thisValue可选:对象作为该执行回调时使用,传递给函数,用作 "this" 的值;如果省略了thisValue ,"this" 的值为 "undefined"。
Finally, I would like to recommend "JavaScript Basics Tutorial" ~ Welcome everyone to learn ~
The above is the detailed content of How to return array elements greater than a specified number via js. For more information, please follow other related articles on the PHP Chinese website!