簡體   English   中英

在 JavaScript 中查找包含字符串的數組的最小/最大元素

[英]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

您可以使用filtertypeof僅檢查數字。

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM