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

JS实现FizzBuzz:如何将替换后的结果推入空数组而非直接打印

FizzBuzz 代码修改方案

你现有的字符串拼接判断逻辑完全正确,不需要调整分支判断部分,只需要补全数组存储逻辑即可。

修改要点

  • Array.push() 加在每次循环内、当前数字对应的结果字符串处理完成的位置即可,也就是你现在写console.log(str)的位置
  • 建议函数执行前先清空全局的results数组,避免多次调用函数时历史结果残留
  • 测试时在函数调用完成后打印results数组即可校验结果

修正后的完整代码

const results = [];

const fizzbuzz = (n) => {
  // 清空历史结果
  results.length = 0;
  for (let i = 1; i <= n; i++) {
    let str = "";

    if (i % 3 === 0) str += "fizz"
    if (i % 5 === 0) str += "buzz"
    if (str === "") str = i;

    // 存入结果数组
    results.push(str);
  }
}

// 测试样例:计算1-15的结果
fizzbuzz(15);
console.log(results);
// 预期输出:[1, 2, "fizz", 4, "buzz", "fizz", 7, 8, "fizz", "buzz", 11, "fizz", 13, 14, "fizzbuzz"]

可选优化写法

如果不需要把results作为全局变量,完全可以把数组声明放到函数内部,最后返回结果,封装性更好,也不需要手动清空历史数据:

const fizzbuzz = (n) => {
  const results = [];
  for (let i = 1; i <= n; i++) {
    let str = "";
    if (i % 3 === 0) str += "fizz"
    if (i % 5 === 0) str += "buzz"
    if (str === "") str = i;
    results.push(str);
  }
  return results;
}

// 测试
const testResult = fizzbuzz(15);
console.log(testResult);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 11:12:21