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

JS函数重构求助:如何用指定字符分隔多个字符串参数?

修复strAdd函数的字符串参数分隔问题

问题根源

你原来的代码里,Array.prototype.slice.call(arguments[i])会把单个字符串参数拆成字符数组(比如'here'变成['h','e','r','e']),所以调用join只会分隔字符串内部的字符,而不是不同字符串参数之间的内容。

重构方案

核心思路是先收集所有字符串参数到一个数组,最后统一用指定分隔符拼接,这样就能实现字符串参数之间的分隔效果,同时避免逐个拼接时需要处理“最后一个参数不加分隔符”的麻烦。

基础版(固定分隔符)

function strAdd() {
    const strParts = [];
    let numResult = 0;
    const separator = ' '; // 可自定义分隔符,比如'-'、','等

    for (let i = 0; i < arguments.length; i++) {
        const arg = arguments[i];
        if (typeof arg === 'string') {
            strParts.push(arg); // 直接存入完整字符串,不拆字符
        } else if (typeof arg === 'number') {
            numResult += arg;
        }
    }

    const strResult = strParts.join(separator);
    console.log(`拼接后的字符串:${strResult},数字累加结果:${numResult}`);
}

调用示例:

strAdd('here', 10, 'are', 10, 2, 'the', 35, 'strings');

输出:

拼接后的字符串:here are the strings,数字累加结果:57

进阶版(支持自定义分隔符)

如果需要每次调用时指定不同分隔符,可以把分隔符作为第一个参数:

function strAdd() {
    const strParts = [];
    let numResult = 0;
    let separator = ' '; // 默认分隔符为空格

    // 判断第一个参数是否为自定义分隔符(非数字的字符串)
    if (arguments.length > 0 && typeof arguments[0] === 'string' && isNaN(arguments[0])) {
        separator = arguments[0];
        // 从第二个参数开始遍历
        for (let i = 1; i < arguments.length; i++) {
            processArg(arguments[i]);
        }
    } else {
        // 无自定义分隔符,从第一个参数开始遍历
        for (let i = 0; i < arguments.length; i++) {
            processArg(arguments[i]);
        }
    }

    // 提取参数处理逻辑,避免重复代码
    function processArg(arg) {
        if (typeof arg === 'string') {
            strParts.push(arg);
        } else if (typeof arg === 'number') {
            numResult += arg;
        }
    }

    const strResult = strParts.join(separator);
    console.log(`拼接后的字符串:${strResult},数字累加结果:${numResult}`);
}

调用示例:

// 用短横线分隔
strAdd('-', 'here', 10, 'are', 10, 2, 'the', 35, 'strings');

输出:

拼接后的字符串:here-are-the-strings,数字累加结果:57

关键改进点

  • 不再拆分单个字符串为字符数组,直接将完整字符串存入数组
  • 利用数组join方法一次性完成所有字符串参数的分隔拼接,逻辑更简洁
  • 进阶版支持自定义分隔符,函数灵活性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:45:28