简体   繁体   English

检查数组中可以成功转换为数字的字符串数

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

Here's a description of the task I'm working on:这是我正在处理的任务的描述:

Write a function called countNumbers, which accepts an array of strings.编写一个名为 countNumbers 的 function,它接受一个字符串数组。 The function should return a count of the number of strings in the array that can be successfully converted into a number. function 应该返回数组中可以成功转换为数字的字符串数。 For example, the string "1" can be successfully converted to the number 1, but the string "hello" cannot be converted into a number.例如,字符串“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

My code:我的代码:

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

When I console log (Number(arr[num]), I do see NaN in the console, however when I'm comparing in the loop, the count variable does not increase and I end up with a return value equal to the length of the array.当我控制台日志 (Number(arr[num]) 时,我确实在控制台中看到了 NaN,但是当我在循环中进行比较时,计数变量不会增加并且我最终得到一个等于长度的返回值阵列。

Any tips on what I could be doing wrong or what I overlooked are much appreciated.非常感谢任何关于我可能做错了什么或我忽略了什么的提示。

You could filter with isFinite and take the length.您可以使用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

If you really like only digits, then you could check with a regular expression.如果您真的只喜欢数字,那么您可以使用正则表达式进行检查。

 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

Filter your arrays and get their lengths.过滤您的 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; }

You must pass n through parseInt() before passing to isNaN() , otherwise the space will evaluate as a 0 and count towards the total.在传递给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 );

Two things straight up:直截了当的两件事:

  1. Loops.循环。
  2. Variables.变量。

When you solve a problem using loops and variables, you now have two problems.当您使用循环和变量解决问题时,您现在有两个问题。

Remove the inline console.log to return the actual count as a number.删除内联console.log以将实际计数返回为数字。

There may be more exhaustive or smarter checks than that, but you can easily modify the isNum function, without touching any of the other code.可能有比这更详尽或更智能的检查,但您可以轻松修改isNum function,而无需触及任何其他代码。

No loops, no variables, and a separation of concerns - the isNum logic is not mixed with control flow.没有循环,没有变量,关注点分离 - isNum逻辑没有与控制流混合。

Update: the parseFloat check in Alex's answer is the smarter check you are looking for.更新: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

Here is the version with the smarter check from Alex's answer.这是亚历克斯回答中带有更智能检查的版本。 The editor doesn't support nullish coalescing, so instead of parseFloat(maybeNum)?? false编辑器不支持无效合并,所以不用parseFloat(maybeNum)?? false parseFloat(maybeNum)?? false , you have to do it like it's still the 90's: 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

Reduce over it and evaluate edge cases减少它并评估边缘情况

 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) }

I think with reduce it can be done我认为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)

You can make use of in-built 'isNaN()' function.您可以使用内置的“isNaN()”function。
Simply replace your if statement with below:只需将您的 if 语句替换为以下内容:

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

The other solutions testing isNaN(Number(character)) are better.其他解决方案测试isNaN(Number(character))更好。 I forgot about isNaN and wrote this.我忘记了isNaN并写了这个。 It performs slower and is much longer.它执行得更慢并且更长。

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