You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现统计指定数字在输入数值中出现次数的JavaScript功能?

实现步骤指导

首先要先做输入验证,避免用户输入不符合要求的内容导致后续逻辑出错:

  • 检查第一个输入是否是0-9的单个数字,不符合就重新提示
  • 检查第二个输入是否是有效数值,不符合也重新提示

接下来是核心的次数统计,给你两种简单可行的实现方式:

方式一:for循环遍历字符串

把输入的数值转换成字符串,直接按位遍历对比计数,逻辑直观:

// 输入验证
while (digit_question.length !== 1 || isNaN(Number(digit_question))) {
  digit_question = prompt("请输入0-9之间的单个数字!");
}
while (isNaN(Number(number_question))) {
  number_question = prompt("请输入有效的数值!");
}

// 统计次数
let count = 0;
const target = digit_question;
const numStr = number_question.toString();

for (let i = 0; i < numStr.length; i++) {
  if (numStr[i] === target) {
    count++;
  }
}

alert(`数字${target}在数值中出现了${count}次`);

方式二:正则表达式匹配

利用正则全局匹配目标数字,直接获取匹配结果的长度,代码更简洁:

// 输入验证同上
while (digit_question.length !== 1 || isNaN(Number(digit_question))) {
  digit_question = prompt("请输入0-9之间的单个数字!");
}
while (isNaN(Number(number_question))) {
  number_question = prompt("请输入有效的数值!");
}

// 统计次数
const regex = new RegExp(digit_question, 'g');
const matches = number_question.toString().match(regex);
const count = matches ? matches.length : 0;

alert(`数字${digit_question}在数值中出现了${count}次`);

关键提示

把数值转成字符串是核心技巧,这样不用拆分数字的每一位,直接按字符对比就行,比操作数字的取模、除法要简单得多。

内容的提问来源于stack exchange,提问作者noobprogrammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:15:38