簡體   English   中英

在JavaScript中從數組中獲取最大值和最小值

[英]Get max and min value from array in JavaScript

我從數據屬性創建以下數組,我需要能夠從中獲取最高和最低值,以便稍后將其傳遞給另一個函數。

var allProducts = $(products).children("li");
prices = []
$(allProducts).each(function () {
    var price = parseFloat($(this).data('price'));
    prices[price] = price;
});
console.log(prices[0]) <!-- this returns undefined

我的列表項看起來像這樣(我已經減少了可讀性):

<li data-price="29.97"><a href="#">Product</a></li>
<li data-price="31.00"><a href="#">Product</a></li>
<li data-price="19.38"><a href="#">Product</a></li>
<li data-price="20.00"><a href="#">Product</a></li>

一個快速的console.log價格顯示我的數組看起來是排序的所以我可以抓住我假設的第一個和最后一個元素,但目前數組中的名稱和值是相同的,所以每當我嘗試做價格[0 ],我得到了不確定

[]
19.38   19.38
20.00   20.00
29.97   29.97
31.00   31.00

有一種感覺這是一個非常簡單的問題,所以請善待:)

要獲取數組中的最小/最大值,您可以使用:

var _array = [1,3,2];
Math.max.apply(Math,_array); // 3
Math.min.apply(Math,_array); // 1

為什么不將它存儲為價格而不是對象?

prices = []
$(allProducts).each(function () {
    var price = parseFloat($(this).data('price'));
    prices.push(price);
});
prices.sort(function(a, b) { return a - b }); //this is the magic line which sort the array

那樣你就可以

prices[0]; // cheapest
prices[prices.length - 1]; // most expensive

請注意,您可以執行shift()pop()分別獲得最低和最高價格,但它會從數組中取消價格。

更好的選擇是使用下面的Sergei解決方案,分別使用Math.maxmin

編輯:

我意識到,如果你有類似[11.5, 3.1, 3.5, 3.7]因為11.5被視為一個字符串,並且會以字典順序排在3.x 之前 ,你需要傳遞自定義排序函數確保它們確實被視為浮動:

prices.sort(function(a, b) { return a - b });

獲得所有這些價格的另一種(可能更簡潔的)方法可能是:而不是.each。

var prices = $(products).children("li").map(function() {
    return $(this).prop("data-price");
}).get();

另外,您可能需要考慮過濾數組以除去空數字或非數字數組值,以防它們存在:

prices = prices.filter(function(n){ return(!isNaN(parseFloat(n))) });

然后使用謝爾蓋的解決方案:

var max = Math.max.apply(Math,prices);
var min = Math.min.apply(Math,prices);

如果您有“分散”(不在數組內)值,您可以使用:

var max_value = Math.max(val1, val2, val3, val4, val5);
arr = [9,4,2,93,6,2,4,61,1];
ArrMax = Math.max.apply(Math, arr);

使用lodash查找數組中的最大和最小數字。

 var array = [1, 3, 2]; var func = _.over(Math.max, Math.min); var [max, min] = func(...array); // => [3, 1] console.log(max); console.log(min); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script> 

使用它,它適用於靜態數組和動態生成的數組。

var array = [12,2,23,324,23,123,4,23,132,23];
var getMaxValue = Math.max.apply(Math, array );

當我嘗試從下面的代碼中查找最大值時,我遇到了問題

$('#myTabs').find('li.active').prevAll().andSelf().each(function () {
            newGetWidthOfEachTab.push(parseInt($(this).outerWidth()));
        });

        for (var i = 0; i < newGetWidthOfEachTab.length; i++) {
            newWidthOfEachTabTotal += newGetWidthOfEachTab[i];
            newGetWidthOfEachTabArr.push(parseInt(newWidthOfEachTabTotal));
        }

        getMaxValue = Math.max.apply(Math, array);

我使用時得到'NAN'

    var max_value = Math.max(12, 21, 23, 2323, 23);

用我的代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM