Javascript在数组中找到最接近的数字
Javascript find closest number in array without going under
我有一个数字数组,例如[300, 500, 700, 1000, 2000, 3000]
,我想找到最接近的数字,而不低于给定的数字。
例如,搜索2200将返回3000(而不是2000)。
然而,如果我搜索3200,因为数组中没有更高的值,它应该返回3000,因为没有其他选择。
我可以使用
得到最接近的值。if (sizeToUse == null || Math.abs(this - monitorWidth) < Math.abs(sizeToUse - monitorWidth)) {
sizeToUse = this;
}
然而,我不能让整个东西工作。我的完整代码是:
$(function() {
var monitorWidth = window.screen.availWidth,
sizeToUse = null,
upscaleImages = false;
$('.responsive-img').each(function(){
var sizeData = $(this).attr('data-available-sizes');
sizeData = sizeData.replace(' ', '');
var sizesAvailable = sizeData.split(',');
sizesAvailable.sort(function(a, b){return b-a});
$.each(sizesAvailable, function(){
if(upscaleImages){
if (sizeToUse == null || Math.abs(this - monitorWidth) < Math.abs(sizeToUse - monitorWidth)) {
sizeToUse = this;
}
}
else{
//We don't want to upscale images so we need to find the next highest image available
}
});
console.log('Size to use ' + sizeToUse + ' monitor width ' + monitorWidth);
});
});
您可以使用以下代码:
function closest(arr, closestTo){
var closest = Math.max.apply(null, arr); //Get the highest number in arr in case it match nothing.
for(var i = 0; i < arr.length; i++){ //Loop the array
if(arr[i] >= closestTo && arr[i] < closest) closest = arr[i]; //Check if it's higher than your number, but lower than your closest value
}
return closest; // return the value
}
var x = closest(yourArr, 2200);
小提琴:http://jsfiddle.net/ngZ32/
另一种方法是查找大于或等于所需元素的第一个候选元素,并获取结果,如果没有匹配则返回最后一个元素:
function closestNumberOver(x, arr) {
return arr.find(d => d >= x) || arr[arr.length - 1]
}
var list = [300, 500, 700, 1000, 2000, 3000];
function findBestMatch(toMatch) {
// Assumes the array is sorted.
var bestMatch = null;
var max = Number.MIN_VALUE;
var item;
for (var i = 0; i < list.length; i++) {
item = list[i];
if (item > toMatch) {
bestMatch = item;
break;
}
max = Math.max(max, item);
}
// Compare to null, just in case bestMatch is 0 itself.
if (bestMatch !== null) {
return bestMatch;
}
return max;
}
alert(findBestMatch(2200));
alert(findBestMatch(3200));
sizesAvailable.sort(function(a, b){return a-b}); // DESCENDING sort
if(upscaleImages) // do th eif once, not every time through the loop
{
$.each(sizesAvailable, function()
{
if (this > monitorWidth)
sizeToUse = this;
}
if (sizeToUse == null) sizeToUse = sizesAvailable[0];
}
else
{
$.each(sizesAvailable, function()
{
//We don't want to upscale images so....
}
}
});
相关文章:
- 如何确定乘以后将使您最接近目标数字的数字
- 将数字四舍五入到最接近的10's放置javascript
- 通过JavaScript将数字舍入到0.11的最接近倍数
- 如何从一组特定的数字中找到最接近的更高数字:javascript
- Javascript:找到最接近的数字
- 如何在 Javascript 中始终将数字四舍五入到最接近的一分钱
- 从数组中获取最接近的数字匹配项,必须更低
- 如何使用 lodash 从数组中获取最接近目标的前两个数字
- 将数字四舍五入到最接近的千,根据数字向上或向下
- 如何确定我的数字最接近哪个数组索引
- Javascript在数组中找到最接近的数字,而不需要重复
- 从数组中获取最接近的数字
- Javascript在数组中找到最接近的数字
- 四舍五入到最接近的指定数字(十进制)
- 根据最接近的数字返回值
- 获取值最接近数字X的JSON数据
- 我如何在数组中找到最接近的数字,而不用遍历
- 从字符串中找到最接近0的数字
- 我有一个数字,我想在jquery数组中得到小于和大于的最接近的数字
- 将数字减少到最接近的 3 的倍数