Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

使用JavaScript写一个函数,扫出字符串中第一个整形数,如果扫不出整数则返回0

  1. User

    使用JavaScript写一个函数,扫出字符串中第一个整形数,如果扫不出整数则返回0

  2. Assistant

    您可以使用正则表达式或循环来实现此功能。以下是使用循环的示例函数代码:

    function findFirstInteger(str) {
      let num = "";
      for (let i = 0; i < str.length; i++) {
        if (!isNaN(parseInt(str[i]))) {
          num += str[i];
        } else if (num !== "") {
          return parseInt(num);
        }
      }
      return num !== "" ? parseInt(num) : 0;
    }
    

    此函数将遍历给定的字符串,每次检查一个字符。如果该字符是数字,则将其添加到字符串num中。如果当前字符不是数字,且num不为空,则将num转换为整数后返回。如果函数遍历完整个字符串后num仍为空,则返回0。

    以下是使用此函数的示例:

    console.log(findFirstInteger("abc123"));  // 输出:123
    console.log(findFirstInteger("123abc"));  // 输出:123
    console.log(findFirstInteger("-456xyz")); // 输出:-456
    console.log(findFirstInteger("xyz"));     // 输出:0
    

    这将输出找到的第一个整数,如果没有找到整数,则输出0。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.