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

如何编写接收10个以上1-100逗号分隔值的JavaScript函数并做运算测试

JavaScript 逗号分隔数值处理函数实现

核心功能代码

/**
 * 处理逗号分隔的数值,先校验再执行基础数学运算
 * @param {string} inputStr 用户输入的逗号分隔字符串
 * @returns {object|boolean} 校验通过返回运算结果对象,校验失败返回false
 */
function processCommaSeparatedNumbers(inputStr) {
    // 校验逗号数量
    const commaCount = (inputStr.match(/,/g) || []).length;
    if (commaCount < 10) {
        alert("comma should be ten or more and the number should be from 1 to 100 not less or more");
        return false;
    }

    // 转换为数字数组
    const numArr = inputStr.split(',').map(item => Number(item.trim()));

    // 校验所有数值是否在合法区间
    const isAllValid = numArr.every(num => {
        return !isNaN(num) && num >= 1 && num <= 100;
    });
    if (!isAllValid) {
        alert("comma should be ten or more and the number should be from 1 to 100 not less or more");
        return false;
    }

    // 执行数学运算,可按需扩展
    const sum = numArr.reduce((prev, curr) => prev + curr, 0);
    const average = sum / numArr.length;
    const max = Math.max(...numArr);
    const min = Math.min(...numArr);
    const sortedArr = [...numArr].sort((a, b) => a - b);
    const median = sortedArr.length % 2 === 1 
        ? sortedArr[Math.floor(sortedArr.length / 2)] 
        : (sortedArr[sortedArr.length / 2 - 1] + sortedArr[sortedArr.length / 2]) / 2;

    return {
        sum,
        average,
        max,
        min,
        median,
        originalArray: numArr
    }
}

测试用例

  • 合法输入测试:调用processCommaSeparatedNumbers("1,2,3,4,5,6,7,8,9,10,11"),符合规则返回运算结果
  • 逗号数量不足测试:调用processCommaSeparatedNumbers("1,2,3,4,5,6,7,8,9"),逗号数量为8,触发提示
  • 数值越界测试:调用processCommaSeparatedNumbers("1,2,3,4,5,6,7,8,9,10,102"),存在102超出区间,触发提示
  • 含非数字测试:调用processCommaSeparatedNumbers("1,2,3,4,5,6,7,8,9,10,test"),存在非数字值,触发提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 20:00:03