簡體   English   中英

檢查數組中可以成功轉換為數字的字符串數

[英]Checking number of strings inside array that can be successfully converted into a number

這是我正在處理的任務的描述:

編寫一個名為 countNumbers 的 function,它接受一個字符串數組。 function 應該返回數組中可以成功轉換為數字的字符串數。 例如,字符串“1”可以成功轉換為數字1,但字符串“hello”無法轉換為數字。

countNumbers(['a','b','3','awesome','4']); // 2
countNumbers(['32', '55', 'awesome', 'test', '100']); // 3
countNumbers([]); // 0
countNumbers(['4','1','0','NaN']); // 3
countNumbers(['7', '12', 'a', '', '6', '8', ' ']); // 4

我的代碼:

function countNumbers(arr) {
    var count = 0;
    for (num in arr) {
        if (Number(arr[num]) !== NaN) {
            count++;
        }
    }
    return count;
}

當我控制台日志 (Number(arr[num]) 時,我確實在控制台中看到了 NaN,但是當我在循環中進行比較時,計數變量不會增加並且我最終得到一個等於長度的返回值陣列。

非常感謝任何關於我可能做錯了什么或我忽略了什么的提示。

您可以使用isFinite進行過濾並獲取長度。

 +'' -> 0 +' ' -> 0

 function countNumbers(array) { return array.filter(isFinite).length; } console.log(countNumbers(['a','b','3','awesome','4'])); // 2 console.log(countNumbers(['32', '55', 'awesome', 'test', '100'])); // 3 console.log(countNumbers([])); // 0 console.log(countNumbers(['4','1','0','NaN'])); // 3 console.log(countNumbers(['7', '12', 'a', '', '6', '8', ' '])); // 4, now 6

如果您真的只喜歡數字,那么您可以使用正則表達式進行檢查。

 function countNumbers(array) { return array.filter(RegExp.prototype.test, /^\d+$/).length; } console.log(countNumbers(['a','b','3','awesome','4'])); // 2 console.log(countNumbers(['32', '55', 'awesome', 'test', '100'])); // 3 console.log(countNumbers([])); // 0 console.log(countNumbers(['4','1','0','NaN'])); // 3 console.log(countNumbers(['7', '12', 'a', '', '6', '8', ' '])); // 4

過濾您的 arrays 並獲取它們的長度。

 console.log(countNumbers(['a', 'b', '3', 'awesome', '4'])); // 2 console.log(countNumbers(['32', '55', 'awesome', 'test', '100'])); // 3 console.log(countNumbers([])); // 0 console.log(countNumbers(['4', '1', '0', 'NaN'])); // 3 console.log(countNumbers(['7', '12', 'a', '', '6', '8', ' '])); // 4 function countNumbers(arr) { return arr.filter(function(el) { return parseFloat(el) == el; }).length; }

在傳遞給isNaN() parseInt()傳遞n ,否則空間將評估為 0 並計入總數。

 const isNum = (n) =>;isNaN(parseInt(n)). const countNumbers = (arr) => arr.filter(isNum);length. console,log( countNumbers(['a','b','3','awesome','4']), // 2 countNumbers(['32', '55', 'awesome', 'test', '100']), // 3 countNumbers([]), // 0 countNumbers(['4','1','0','NaN']), // 3 countNumbers(['7', '12', 'a', '', '6', '8'; ' ']) // 4 );

直截了當的兩件事:

  1. 循環。
  2. 變量。

當您使用循環和變量解決問題時,您現在有兩個問題。

刪除內聯console.log以將實際計數返回為數字。

可能有比這更詳盡或更智能的檢查,但您可以輕松修改isNum function,而無需觸及任何其他代碼。

沒有循環,沒有變量,關注點分離 - isNum邏輯沒有與控制流混合。

更新:Alex 的答案中的parseFloat檢查是您正在尋找的更智能的檢查。

 const isNum = maybeNum => (typeof maybeNum === 'number' || typeof +maybeNum === 'number') &&.isNaN(+maybeNum) && maybeNum.= '' && maybeNum.= ' ' const countNumbers = arr => console,log(arr,filter(isNum),length) countNumbers(['a','b';'3','awesome','4']), // 2 countNumbers(['32', '55'; 'awesome'; 'test', '100']), // 3 countNumbers([]), // 0 countNumbers(['4';'1','0','NaN']), // 3 countNumbers(['7', '12', 'a', ''; '6', '8', ' ']); // 4

這是亞歷克斯回答中帶有更智能檢查的版本。 編輯器不支持無效合並,所以不用parseFloat(maybeNum)?? false parseFloat(maybeNum)?? false ,你必須像 90 年代那樣去做:

parseFloat(maybeNum) || parseFloat(maybeNum) === 0

 const isNum = maybeNum => parseFloat(maybeNum) || parseFloat(maybeNum) === 0 const countNumbers = arr => arr.filter(isNum).length const test = arr => console.log(countNumbers(arr)) test(['a','b','3','awesome','4']); // 2 test(['32', '55', 'awesome', 'test', '100']); // 3 test([]); // 0 test(['4','1','0','NaN']); // 3 test(['7', '12', 'a', '', '6', '8', ' ']); // 4

減少它並評估邊緣情況

 console.log(countNumbers(['a','b','3','awesome','4'])); // 2 console.log(countNumbers(['32', '55', 'awesome', 'test', '100'])); // 3 console.log(countNumbers([])); // 0 console.log(countNumbers(['4','1','0','NaN'])); // 3 console.log(countNumbers(['7', '12', 'a', '', '6', '8', ' '])); // 4 function countNumbers(arrayStrings) { return arrayStrings.reduce((count, string) => isNaN(string) || string.trim() === ''? count: count + 1, 0) }

我認為reduce它可以完成

 const countNumbers = arr => { return arr.reduce((acc, value) => isNaN(Number(value))? acc: acc + 1, 0) } const num = countNumbers(['a','b','3','awesome','4']); console.log(num)

您可以使用內置的“isNaN()”function。
只需將您的 if 語句替換為以下內容:

if (!isNaN(arr[num])){

其他解決方案測試isNaN(Number(character))更好。 我忘記了isNaN並寫了這個。 它執行得更慢並且更長。

function countNumbers(array) {
    let count = 0
    for (number of array) {
      if(typeof number === 'number') {
        count++
      } else if(typeof number === 'string') {
        let isNumber
        let numberCharacters = number.split('')
        const numberRegularExpression = new RegExp(/[0-9]/)
        for(character of numberCharacters) {
          if(numberRegularExpression.test(character) !== true) {
            isNumber = false
            break
          } else {
            isNumber = true
          }
        }
        if(isNumber === true) count++
      }
    }
    return count;
}

暫無
暫無

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

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