Math.min.apply为null返回0 [英] Math.min.apply returns 0 for null

查看:237
本文介绍了Math.min.apply为null返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从数组中获得最小值。如果数据包含 null 值,则 Math.min.apply 返回 0 for null value。请参阅此JSFiddle示例。即使数组中存在空值,如何获得真正的最小值?

I would like to get minimum value from an array. If the data contains null value, Math.min.apply returns 0 for null value. Please see this JSFiddle example. How can I get true minimum value even if null value exists in array?

代码(与JSFiddle示例中相同):

Code (same as in JSFiddle example):

var arrayObject= [ {"x": 1, "y": 5}, {"x": 2, "y": 2}, {"x": 3, "y": 9}, {"x": 4, "y": null}, {"x": 5, "y": 12} ];

var max = Math.max.apply(Math, arrayObject.map(function(o){return o.y;}));
var min = Math.min.apply(Math, arrayObject.map(function(o){return o.y;}));

$("#max").text(max);
$("#min").text(min);


推荐答案

嗯, null 是 0 。如果您不想要考虑 null 值,则必须将其过滤掉:

Well, the numerical value for null is 0. If you don't want null values to be be considered, you have to filter them out:

var values = arrayObject.map(function(o){
    return o.y;
}).filter(function(val) {
    return val !== null
});

参考 Array#filter

这篇关于Math.min.apply为null返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆