选择数量最多比数组变量较小 [英] Selecting biggest number smaller than a variable in array

查看:130
本文介绍了选择数量最多比数组变量较小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript数组,像这样一个变量;

I have a JavaScript array and a variable like so;

var a = [0, 1200, 3260, 9430, 13220],
    b = 4500;

什么是选择这仍然小于或等于变量?

What would be the smartest way to select the largest value in the array that's still smaller than or equal to the variable?

在这个例子中,我需要选择 3260

In this example, I'd need to select 3260.

我可以做这样的事情;

I could do something like this;

$.each(a, function(i){
    if(a[i] <= b && a[i+1] > b){
        var c = a[i];
        return false;
    }
});

但我想,如果选择的数组值是最后一个,可能无法正常工作。更何况,对我来说,它看起来像很多code的东西很简单。

But I'm thinking that might not work if the selected array value is the last one. Not to mention, to me it looks like a lot of code for something rather simple.

有没有达到我后的一个聪明/更简洁的方式?

Is there a smarter/less verbose way of achieving what I'm after?

(是的,我知道我不应该用一个jQuery环路这一点,但打字时的例子我很懒)

推荐答案

您可以到它是通过阵列过滤的组合和应用()的另一种方式,我认为这是一个非常可读的方式。
呼叫筛选()只返回元件在一数组,它不满足predicate功能,然后应用()与每个元素作为参数调用Math.max

Another way you could to it is through a combination of array filtering and apply(), which I think is a very readable approach. The call to filter() just returns an array of elements in a which don't satisfy the predicate function and then apply() calls Math.max with each element as an argument.

var a = [1, 2, 3, 4, 5];
var b = 4;
var result = Math.max.apply(Math, a.filter(function(x){return x <= b}));

结果将等于4。

这篇关于选择数量最多比数组变量较小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆