【发布时间】:2021-11-17 03:18:58
【问题描述】:
我试图保存一个随机数,在 J 中只有一次。
let Machine = {
position : 0,
num_move : 0,
isEmpty : true,
memory : [],
start : function () {
for (let index = 0; index < 9; index++) {
this.memory.push({move:undefined,isEmpty: true})
}
},
generateMove:function () {
let num = Math.floor((Math.random()*9)+1)
if (num>=10) {
num-=1
}
return num
},
// Update move
move : function () {
let move = this.generateMove()
let prev = this.num_move
if (!this.memory[this.num_move] && this.num_move<=0) {
this.memory[this.num_move]=move
this.num_move+=1
}
},
//Return data values
data : function () {
return {
memory : this.memory,
num_move : this.num_move
}
}
}
问题是 Javascript 保存一个新的随机数,但我只想保存一次。就像记忆一样。
Machine.move() //First time
console.log(Machine.data())
// {memory : [2], num_move : 1}
Machine.move() //Second time
console.log(Mahine.data())
// {memory : [9], num_move : 1}
我也尝试使用 start 方法初始化机器对象。并像这样改变移动方法。在推送内存之前检查是否为空
move : function () {
let move = this.generateMove()
if (this.memory[this.num_move].isEmpty) {
this.memory[this.num_move].isEmpty = false
this.memory[this.num_move].move=move
this.num_move+=1
}
}
但它不起作用。每当我从控制台调用时,JS 都会生成一个新的随机数。
【问题讨论】:
-
我认为你的问题是
this.num_move<=0。您确定要仅在num_move小于或等于 0 时添加新元素吗?另外,我认为您可以在数组上使用.push()而不是整个if语句。
标签: javascript arrays memory