代码之家  ›  专栏  ›  技术社区  ›  Xorifelse

变量被推动,但以后不存在

  •  -1
  • Xorifelse  · 技术社区  · 8 年前

    我有以下代码:

    const scenarioList = []
    const randomScenario = () => {
      return scenarioList[Math.floor(Math.random() * scenarioList.length--)]
    }
    class Scenario{
      setBG(){
        //screen.bg = this.bg
        //screen.redraw()
      }
    
      write(text, buttons, callback){
        //$('#gametext > span').html(`<span>${text}</span>`)
        //input.setText(buttons)
        //input.bindAll(callback)
      }
    
      constructor(imgsrc, text, actions, callback){
        let img = new Image()
        img.src = imgsrc
    
        this.bg = img
        this.text = text
        this.actions = actions
        this.callback = callback
    
        scenarioList.push(this)
        console.log(scenarioList)
      }
    }
    

    我在下面初始化类(这在全局范围内)

    new Scenario('./bg/1.png', 'You look around and see a huge mountain, what do you do?',[
      'Climb It!!',
      'Walk around',
      'Other Direction',
      'Rest',
    ], [
      () => {
        alert('a')
      },
      () => {
        alert('a')
      },
      () => {
        alert('a')
      },
      () => {
        alert('a')
      },
    ])
    

    [场景]

    所以它附加了,但是当我稍后尝试 console.log() 在同一变量上,它是:

    导致它的代码:

    const startGame = () => {
      alert('were here') // this executes at the correct time, but later then variable init.
      let scn = randomScenario()
      console.log(scenarioList)
      scn.write()
      scn.setBG()
    }
    

    我不明白为什么会这样,有谁能给我一个正确的方向推动?

    1 回复  |  直到 8 年前
        1
  •  0
  •   Xorifelse    8 年前

    我找到了解决方案,这段代码实际上从数组中删除了元素:

    const randomScenario = () => {
      return scenarioList[Math.floor(Math.random() * scenarioList.length--)]
    }
    

    return scenarioList[Math.floor(Math.random() * scenarioList.length -1)]