变量已推送,但以后不存在

时间:2018-08-11 14:29:36

标签: javascript

我有以下代码:

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(scenarioList)进行验证

  

[场景]

因此它是附加的,但是当我稍后尝试在同一变量上执行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 个答案:

答案 0 :(得分:0)

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

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

相反,我是这样做的:

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