创建函数时使用push方法遇到困难

问题描述 投票:0回答:1

我想创建一个函数,将“我有 1 瓶。我有 2 瓶。我有 3 瓶”等等记录到控制台。 但我不断得到以下输出:

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()

javascript arrays methods
1个回答
0
投票

let word = []
let x = 1

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

  x++
}

test()
test()
test()

这样?

© www.soinside.com 2019 - 2024. All rights reserved.