给定一个数组,例如:var arr = [
['1','15','56'],
['1','15','56'],
['3','-','56'],
['1','78','-'],
['1','-','56'],
]如图所示不规则的二维数组求其最大值,有什么优雅点的方法吗?
2 回答
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
es6很简单,如果二维数组是纯数字的话这样
const max = Math.max(...[].concat(...arr)); console.log(max)
不过我看你数组中包含-
这样的字符,就要先过滤一遍
const max = Math.max(...[].concat(...arr.map(_arr => _arr.map(v => isNaN(v) ? 0 : v))));console.log(max)
es5就乖乖循环遍历吧,怎么写都是丑的
var max = 0; arr.forEach(function (_arr) { _arr.forEach(function (v) { if (!isNaN(v) && v > max) max = v }) }); console.log(max)
倚天杖
TA贡献1828条经验 获得超3个赞
var arr = [ ['1','15','56'], ['1','15','56'], ['3','-','56'], ['1','78','-'], ['1','-','56'], ];function dparseInt(i){ var j = parseInt(i); if( isNaN(j) ) return 0; return j;var arr = [ ['1','15','56'], ['1','15','56'], ['3','-','56'], ['1','78','-'], ['1','-','56'], ];function dparseInt(i){ var j = parseInt(i); if( isNaN(j) ) return 0; return j; }//数组全是字符先转为数字var arr1 = arr.map(item=>{ return item.map(i => dparseInt(i)); });console.log(arr1);//两个Math.max 搞定var result = Math.max(...arr1.map(v=>Math.max(...v)))console.log(result)
添加回答
举报
0/150
提交
取消