Get max and min value from array in JavaScript

前端 未结 7 1180
小鲜肉
小鲜肉 2020-12-07 22:26

I am creating the following array from data attributes and I need to be able to grab the highest and lowest value from it so I can pass it to another function later on.

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 22:48

    use this and it works on both the static arrays and dynamically generated arrays.

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

    I had the issue when I use trying to find max value from code below

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

    I was getting 'NAN' when I use

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

    with my code

提交回复
热议问题