2014-07-31 22 views
9

Ho una matrice di numeri, ad esempio [300, 500, 700, 1000, 2000, 3000] e voglio trovare il numero più vicino, senza andare sotto il numero indicato.Javascript trova il numero più vicino nell'array senza passare sotto

Ad esempio, la ricerca di 2200 restituisce 3000 (NON 2000).

Tuttavia, se cerco 3200 perché non c'è niente di più alto nell'array, dovrebbe restituire 3000 in quanto non ci sono altre scelte.

posso ottenere il numero più vicino che si trova sotto il valore con:

if (sizeToUse == null || Math.abs(this - monitorWidth) < Math.abs(sizeToUse - monitorWidth)) { 
       sizeToUse = this; 
      } 

Tuttavia, non riesco a ottenere il tutto al lavoro. Il mio codice completo è:

$(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); 

}); 


}); 
+1

è array ordinato? – dfsq

+0

Potresti rimuovere il 3/4 del codice che non ha nulla a che fare con la domanda? –

+0

Ho ordinato l'array usando: sizesAvailable.sort (function (a, b) {return b-a}); – Amo

risposta

6

È possibile utilizzare questo codice:

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); 

Fiddle: http://jsfiddle.net/ngZ32/

+0

Questo sembra fare esattamente ciò di cui ho bisogno con l'importo minimo di codice. Ottima risposta Grazie – Amo

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)); 
0
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.... 
    } 
} 
}); 
Problemi correlati