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

如何从文本中排除字符串并提取数字求和?

实现JavaScript函数specialMix的解决方案

需求说明

实现specialMix函数,接收任意数量参数,规则如下:

  • 参数为数字类型时,直接累加;
  • 参数为包含数字的字符串时,提取其中的开头连续数字进行累加;
  • 若所有参数均为不含数字的纯字符串,返回"All Is Strings."。

完整实现代码

function specialMix(...data) {
    let result = 0;
    let hasValidNumber = false;

    for (const item of data) {
        if (typeof item === 'number') {
            result += item;
            hasValidNumber = true;
        } else if (typeof item === 'string') {
            const num = parseInt(item, 10);
            if (!isNaN(num)) {
                result += num;
                hasValidNumber = true;
            }
        }
    }

    return hasValidNumber ? result : "All Is Strings.";
}

测试用例验证

调用函数并验证结果:

console.log(specialMix(10, 20, 30)); // 输出:60
console.log(specialMix("10Test", "Testing", "20Cool")); // 输出:30
console.log(specialMix("Testing", "10Testing", "40Cool")); // 输出:50
console.log(specialMix("Test", "Cool", "Test")); // 输出:All Is Strings.

代码说明

  • 用...data剩余参数语法接收任意数量输入;
  • 遍历参数时区分类型处理:
    • 数字直接累加,同时标记存在有效数字;
    • 字符串通过parseInt提取开头连续数字,提取有效则累加并标记;
  • 最后根据是否存在有效数字,返回累加结果或指定提示字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:24:25