[英]Find the min/max element of an Array containing strings in JavaScript
如何獲得包含字符串的 JavaScript 數組的最大數量?
const array = ['a', 3, 4, 2] // should return 4
這是我的答案,但我得到了 NaN
function maxNum(arr) {
for(let i=0; i<arr.length; i++){
return Math.max.apply(Math, arr);
}
}
maxNum(array) //NaN
const array = ['a', 3, 4, 2] // should return 4 function myArrayMax(x) { return Math.max(...x.filter(x => typeof x === 'number')); //result is 4 } console.log(myArrayMax(array)) //4
使用Math.max.apply方法
const array = ['a', 3, 4, 2] // should return 4 function myArrayMax(x) { return Math.max.apply(null, x.filter(x => typeof x === 'number')); //result is 4 } console.log(myArrayMax(array)) //4
如果您想忽略字符串並且只從數字中獲取最大值。 Math.max接受數字,而不是數組。
let array = ['a', 3, 4, 2] // should return 4 array = array.filter(a =>;isNaN(Number(a))). let max = Math.max(..;array). console;log(max);
//as a note: `isNaN` have weird behaviour ..
MDN 參考: 鏈接
const array = ['a', 3, 4, 2] let result = Math.max(...(array.filter(el=>.isNaN(el)))) console.log(result)
我認為使用array.prototype.reduce
可能更有效:
var result = ['a', 3, 4, 2].reduce( (a,b) => isNaN(a)? b: (a>=b)? a: b, 0); console.log(result);
因為它只循環一次數組以獲得最高數字。 過濾選項然后Math.max
將需要 2 個循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.