JS声称656 <7是真的

Tim*_*kiy 0 javascript jquery json

我有一个结构的json数组:

 { data : [ { "num" : val , "time" : val } , ... ] }
Run Code Online (Sandbox Code Playgroud)

我需要找到num的最大值,最小/最大时间,以及将对象移动到元组数组中:

 [[time,num]...]
Run Code Online (Sandbox Code Playgroud)

为了做到这一点,我使用以下结构(它是一个成功的回调回调,输出是json字符串):

        var json = $.parseJSON(output);

        var xmin = json.data[0].time ; 
        var xmax = json.data[0].time ; 
        var ymax = json.data[0].num  ;

        var data = [];

        //console.log(Math.max.apply(Math,json.data.num));

        for( i = 0 ; i < json.data.length ; i++){
            if( json.data[i].time < xmin){ 
                xmin = json.data[i].time;
            }
            if( json.data[i].time > xmax){ 
                xmax = json.data[i].time;
            }

            if(  ymax < json.data[i].num  ){ 
                console.log(ymax + " " + json.data[i].num + "b " + (ymax > json.data[i].num) );                 
                ymax = json.data[i].num ;
                console.log(ymax + " " + json.data[i].num+ "a");
            }

            data.push([json.data[i].time,json.data[i].num]);
        }
Run Code Online (Sandbox Code Playgroud)

我知道最后ymax是7,这个logget到控制台:

....
607 607a
607 646b true
646 646a
646 656b true
656 656a
656 7b true
7 7a
Run Code Online (Sandbox Code Playgroud)

如你所见,声称656 <7是真的.我不是异步大师,任何帮助将不胜感激.

mus*_*uel 5

在比较之前,请务必将字符串正确转换为数字:

var ymax = parseInt(json.data[0].num, 10);

....

var ycur = parseInt(json.data[i].num, 10);
if(  ymax < ycur  ){ 
    console.log(ymax + " " + ycur + "b " + (ymax > ycur) );                 
    ymax = ycur;
    console.log(ymax + " " + ycur + "a");
}
Run Code Online (Sandbox Code Playgroud)

如果您没有真正需要进行比较,并且只想跟踪最大值,您可以在循环中对其进行单行处理:

ymax = Math.max(ymax, parseInt(json.data[i].num, 10));
Run Code Online (Sandbox Code Playgroud)