我在 Javascript 中创建了一个应该全是数字的数组。当我对其使用 Math.max
时,该函数返回 NaN
。我很困惑。
首先,我知道documentation says当参数之一无法转换为数字时,Math.max 返回 NaN,所以我认为这种情况正在发生。我无法理解那是什么。
这里d
是一个对象数组。这些对象是键值对。我想将 d 数组中每个对象的所有值放入一个新数组中,然后找到最大值。以下是我制作新数组 valsarr
的方法:
var valsarr = [];
d.map(function(row){
Object.keys(row).forEach(function(key) {
row[key] = Number(row[key]);
valsarr.push(Number(row[key]));
});
});
我知道使用 Number
两次是多余的,但我添加了第二次以格外小心。我尝试了 parseInt
和 +
代替它,并得到了相同的结果。
然后我尝试获取该数组的最大值并打印:
var mymax = Math.max.apply(Math, valsarr)
console.log(mymax);
它打印NaN
作为调试过程的一部分,我尝试过滤数组以查找其中的非数字,但我什么也没得到。然而,我的该任务代码也可能有错误。这是:
function isNotNumber(value) {
return (typeof(value) !== "number");
}
var badarr = valsarr.filter(isNotNumber);
console.log('Filtered Array\n', badarr);
它打印一个长度为 0 的数组。我相信这意味着它在数组中没有找到非数字值。
还有两点注意:d
中的原始数据包含数千个值。它来自 .csvs。所以我不想搜索所有值来查找非数字的值。我可以很容易地看到原始的 d 对象和 valsarr 数组中确实有数字。其次,当我加载我正在使用的 .csv 文件之一而不是其他任何文件时,它会起作用。
但是,对于任何 .csv,当我扫描它们进行检查时,d
和 valsarr
中都至少有一些数字,所以第一个代码块正在做某事,至少每次都是这样。
任何帮助将不胜感激。
最佳答案
Math.max接受多个参数,而不是数组。您可以使用传播(ES7)
Math.max(...[1,2,3,4])
或者您可以使用应用:
Math.max.apply(null,[1,2,3,4])
确保从数组中取出任何不是 laxydeveloper 建议的数字的内容:
Math.max.apply(null,array.filter(x=>!isNaN(x))
在您的代码中,它看起来像这样:
var d = [
{p:"hello"},
{d:2},
{q:7},
{other:1,highest:10},
{q:7}
];
var highest = Math.max.apply(
null,
d.map(
row=>
Object.keys(row).map(
key=>
Number(row[key])
)
).reduce(//flatten array of arrays [[1,2],[2,3]] to [1,2,3,4]
(all,item)=>all.concat(item),
[]
).filter(//take out all that are not numbers
x=>!isNaN(x)
)
);
console.log("highest:",highest);
如果你想知 Prop 有最高值的对象的索引和键,你可以这样做:
var d = [
{p:"hello"},
{d:2},
{q:7},
{other:1,highest:10},
{q:7}
];
//get highest value,index and the key
const [highestVal,highestKey,highestIndex] = d.map(
(item,index)=>
Object.keys(item).reduce(
(all,key)=>all.concat([[item[key],key,index]]),//val,key,index
[]
)
).reduce(
(highest,item)=>{
return item.reduce(
(highest,[val,key,index])=>{
return (val>highest[0])
? [val,key,index]
: highest
},
highest
)
},
[-Infinity,undefined,undefined]
);
console.log(
"highest value:",highestVal,
"highest object",d[highestIndex],
"highest key of that object:",highestKey
);
关于javascript - 创建数字数组后,Math.Max 在数组上返回 Nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48819389/