【问题标题】:How to save a random number, just one time, in Javascript如何在Javascript中只保存一次随机数
【发布时间】: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&lt;=0。您确定要仅在 num_move 小于或等于 0 时添加新元素吗?另外,我认为您可以在数组上使用 .push() 而不是整个 if 语句。

标签: javascript arrays memory


【解决方案1】:

我只是试了一下,保存了对象,两回合都得到了相同的结果。

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
        }
    }
}


var obj = Object.create(Machine);

obj.move();
console.log(obj.data());
// {memory : [2], num_move : 1}

obj.move();
console.log(obj.data());
// {memory : [2], num_move : 1}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 2015-03-15
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多