简体   繁体   中英

Compare Numbers in Javascript array to get largest number

I seem to have the right syntax but i keep getting a NaN value, i believe it has something to do with the propagation of the array, please could you check the code and see where i am going wrong.

var _array = new Array();

var _first = 1;
var _second = 4;

$('#con > div').each(function(index){

    var _data = $(this).css('left').split('px')[0];
    var _class = $(this).attr('class').split(' ')[0];

    _array[_first] = [_data];
    //_array[_second] = _class;

    _first++;
    _second++;

    if(index == 2){
        _first = 1;
        _second = 4;

        for(var i = 0; i < _array.length; i++)
        console.log(_array[i]);

        var large = Math.max.apply(Math, _array);
        console.log(large);

    }
});

Thanks

http://jsfiddle.net/LTMbr/1/

So, I modified it a bit to see - http://jsfiddle.net/LTMbr/4/ and your _array[0] is undefined. So that's why your call to Math.max is returning NaN.

The problem is that you are populating your array starting at index 1. If any of the arguments to Math.max cannot be converted to a number, NaN is returned
This is the case because _array[0] is undefined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM