一个变量没有在我的 JavaScript 工厂函数中得到更新

时间:2021-08-01 16:01:52

标签: javascript variables scope

所以我基本上是在执行下面的代码时尝试更改变量“状态”。

const Ship = (length) => {
  let status = "good"
  let array = []

  for (let i = 1; i <= length; i++) {
    array.push(i)
  }

  const hit = (number) => {
    if (!number) {
      return array
    }
    array[number - 1] = number + 10
    status = "bad"
  }

  return {
    length,
    hit,
    array,
    status
  }
}

const ships = Ship(2)

console.log(ships.status) //initial status
console.log(ships.array) //initial array
ships.hit(1)
console.log(ships.array) //modified array
console.log(ships.status) //not modified status

它应该可以工作,因为数组被修改了,但由于某种原因它没有。 我想知道为什么它不起作用,而不是解决方法。

2 个答案:

答案 0 :(得分:0)

您声明了 hit 函数但没有运行它,

  const hit = (number) => {
    if (!number) {
      return array
    }
    array[number - 1] = number + 10
    status = "bad"
  }
  
  hit(number)   <---

答案 1 :(得分:0)

您将通过闭包获得函数作用域中 status 变量的副本。我建议为您的用例使用 class semantics

class Ship {
    constructor(length) {
        this.array = []
        this.status = "good"
        
        for (let i = 1; i <= length; i++) {
            this.array.push(i)
        }
    }

    hit = (number) => {
        if (!number) {
          return this.array
        }
        this.array[number - 1] = number + 10
        this.status = "bad"
    }
}