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

JavaScript使用push方法创建计数函数时的输出异常问题

问题解决:输出正确的瓶子数量文本

需求与错误输出

想要实现一个函数,在控制台输出类似这样的内容:

I have 1 bottle. I have 2 bottles. I have 3 bottles.

但实际得到的错误输出是:

I have 1 bottle
I have 1 bottle,bottle
I have 1 bottle,bottle,bottle

原代码

let word = []

function test() {
  let x = 1
  if (x <= 1) {
    word.push("bottle")
    console.log("I have " + x + " " + word)
  } else if (x > 1) {
    word.push("bottles")
    console.log("I have " + x + " " + word)
  }

  x++
}

test()
test()
test()

错误原因分析

  1. 全局数组累积问题:word是全局数组,每次调用test()都会往里面push新单词,数组长度持续增加,输出时数组会被自动转为逗号分隔的字符串,所以出现重复的"bottle"。
  2. 局部变量重置:x是函数内部的局部变量,每次调用test()都会重新赋值为1,后续的x++不会影响下一次调用的x值,导致x永远是1。
  3. 格式缺失:输出内容没有加上目标格式里的句点。

修正后的代码

方式一:用函数属性保存计数

function test() {
  // 初始化计数,只在第一次调用时执行
  if (typeof test.count === 'undefined') {
    test.count = 1
  }
  const count = test.count
  // 根据计数直接判断单复数,无需数组
  const bottleWord = count <= 1 ? "bottle" : "bottles"
  // 补全句点,用模板字符串更简洁
  console.log(`I have ${count} ${bottleWord}.`)
  // 计数递增
  test.count++
}

test()
test()
test()

方式二:通过参数传递计数(更推荐)

function test(count) {
  const bottleWord = count <= 1 ? "bottle" : "bottles"
  console.log(`I have ${count} ${bottleWord}.`)
}

// 调用时传入对应计数
test(1)
test(2)
test(3)

正确输出结果

两种方式都会得到符合预期的输出:

I have 1 bottle.
I have 2 bottles.
I have 3 bottles.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 22:50:09