【问题标题】:Return the first integer present in the string返回字符串中存在的第一个整数
【发布时间】:2020-10-13 11:25:48
【问题描述】:

我正在尝试解决来自 jshero.net 的挑战。挑战是:

编写一个函数 parseFirstInt,它接受一个字符串并返回 字符串中存在的第一个整数。如果字符串不包含 整数,你应该得到 NaN。 parseFirstInt('No. 10') 应该返回 10 并且 parseFirstInt('Babylon') 应该返回 NaN。 我想出的解决方案是:

function parseFirstInt(num){
let input=parseInt();
if(Number.isNaN(num)){
return NaN} else {
return num[0]}

}

但它不起作用。它返回以下错误:

parseFirstInt('No. 10') 不返回 10,而是返回 'N'。

测试错误!更正错误并重新运行测试!

你们有什么解决办法吗?

【问题讨论】:

  • num.match(/\d+/)?.[0] ?? NaN
  • 如果你只是想让它工作,而不关心解决方案是否丑陋:使用 digitFound 标志设置为 false,结果设置为 NaN,done 设置为 false,然后遍历字符字符串的,只要未完成且不是字符串结尾,如果 digit 而不是 digitFound:result=digit,如果 digit 和 digitFound:result+=digit,如果不是 digit 和 digitFound:done=true。当循环退出时,int=Number(result)。
  • 我尝试使用num.match(/\d+/)?.[0] ?? NaN,但出现以下错误:parseFirstInt('No. 10') 不返回 10,但未定义。测试错误!更正错误并重新运行测试!
  • 负数也是如此。您可以在正则表达式中添加可选的-return parseInt(num.match(/-?\d+/)?.[0], 10);

标签: javascript arrays parseint


【解决方案1】:

我肯定会为此使用正则表达式。

使用这里写的内容来替换所有字符串

Get the first integers in a string with JavaScript

然后我会检查长度是否为0。如果不是则返回NaN,然后​​parseInt

【讨论】:

    【解决方案2】:

    这应该有效:

        function parseFirstInt(text){
        
           for(let i=0;i<text.length;i++){
              if(text.charCodeAt(i)<58 && text.charCodeAt(i)>47){
                  return text[i];
               } 
           }
           return NaN;
        }
    

    【讨论】:

    • 我现在试了一下,得到以下错误:parseFirstInt('No. 10') 不返回 10,而是返回 '1'。测试错误!更正错误并重新运行测试!
    • 我以为你想要Int 的第一个数字对不起,如果你想要整个 Int 你应该使用matches=text.match(/(\d+)/); 并返回`matches[0]`。
    【解决方案3】:

    match() 函数中使用/[-+]?[0-9]+/g,您可以找到并解析字符串中存在的第一个整数。

    function parseFirstInt(num){
      const ints = num.match(/[-+]?[0-9]+/g)
      return ints ? Number(ints[0]): NaN
    }
    
    console.log(parseFirstInt('No. 10'));
    console.log(parseFirstInt('NaN'));
    console.log(parseFirstInt('No. -10'));

    【讨论】:

      猜你喜欢
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多