本文介绍了计算两个输入值之间的数组中的值数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所示,我想创建一个函数来计算用户输入的两个值之间数组中的值数量.因此,例如,如果数组是[1, 4, 6, 7, 8, 6]
,并且用户输入5
作为他们的第一个值,并且输入7
作为他们的第二个值,则会向他们发出警告,提示说
As the title suggests, I want to create a function the counts the number of values in my array between two values that have been entered by the user. So for example, if the array was [1, 4, 6, 7, 8, 6]
and the user entered 5
as their first value and 7
as their second value, they would be greeted with an alert that said
推荐答案
您可以利用 Array#filter
(设置为选择的回调提供的this
绑定):
var array = [1, 4, 6, 7, 8, 6]
function inRange (x) {
return this[0] <= x && x <= this[1]
}
var result = array.filter(inRange, [5, 7]).length
console.log('Total number of values:', result)
这篇关于计算两个输入值之间的数组中的值数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!