簡體   English   中英

給定包含數字和字符串的數組,Javascript返回數字小於100

[英]Javascript return number less than 100 given an array with numbers and strings

如下所示,我該如何編寫一個返回小於100的數字的函數?

const myArray = ['hello', 3, true, 18, 10,, 99 'ten', false]

const isLessThan100 = (array) => {
  // how to do this? Solution enter here
}

我認為它涉及filter方法,但是我不確定如何同時過濾小於100的數字和不是字符串的數字。

提前致謝!

您可以先檢查它是否是數字

const myArray = ['hello', 3, true, 18, 10, 99, 'ten', false];

const isLessThan100 = myArray.filter(item => {
  return (typeof item === "number") && item < 100;
});

typeof運算符返回一個字符串,該字符串指示未評估的操作數的類型。

你可以先檢查是否typeof的產品number或沒有,然后檢查它是否小於100

您可以通過刪除花括號將代碼減少到一行。

嘗試使用Array.prototype.filter() ,方法如下:

 const myArray = ['hello', 3, true, 18, 10,, 99, 'ten', false] const isLessThan100 = (array) => array.filter(num => typeof(num) === "number" && num < 100); console.log(isLessThan100(myArray)) 
 const isLessThan100 = (array) 

這是一個使用filter的矮個子:

 const myArray = ['hello', 3, true, 18, 10, 99, 101, 'ten', false]; const isLessThan100 = a => a.filter(e => +e === e && e < 100); console.log(isLessThan100(myArray)); 

為了只獲取一個值,可以減少數組。

 const array = ['hello', 3, true, 18, 10,, 99, 'ten', false], isLessThan100 = array => array.reduce((r, v) => typeof v === 'number' && v < 100 && (typeof r !== 'number' || v > r) ? v : r, undefined); console.log(isLessThan100(array)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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