如何在以下函数中使用parseInt或parseFloat忽略非数字参数?

 function highestNumber(num1, num2, num3) {
      var highest = Math.max(num1, num2, num3);
      return highest;
 }

 alert(highestNumber(26,1,109));

最佳答案

我认为parseIntparseFloat在这里没有任何用处。您可以简单地测试一个值是否为数字,是否filter out所有非数字值:

return Math.max.apply(Math, Array.prototype.filter.call(arguments, function(value) {
    return typeof value === 'number';
}));


arguments是一个类似数组的对象,其中包含所有传递给该函数的参数。但是由于它不是实际的数组,所以我们必须使用Array.prototype.<method>.call在其上使用数组方法。

.apply允许您通过仅将数组作为第二个参数传递来调用参数数量未知的函数。



如果您想允许数字字符串,例如"123",您可以改为使用isNaN(以及一些针对null和空字符串的防护措施):

return Math.max.apply(Math, Array.prototype.filter.call(arguments, function(value) {
    return value != null && value !== "" && !isNaN(value);
}));


为什么要对null""进行额外的测试?因为Number("")Number(null)返回0,所以isNaN都将返回false(但是我们仍然要排除这些值)。

08-15 18:38
查看更多