如何从对象中包含的数组中输出随机值

时间:2018-11-03 11:43:16

标签: javascript arrays object

//how to output random values from within an array contained in an object?

var dog = {
        name: "Fluffy",
        leash: [true, false],

        randomizer: function() {
            this.leash[Math.floor(Math.random() * this.leash.length)];
            return this.leash;
            },

        call: function() {
            alert("Honey, " + this.name + " needs to pee…");
        },

        response: function() {
            alert("Ok, i got it, dear…");
            if (this.leash = false) {
                alert("You've got to put his leash on first");
            } else alert("Enjoy your walk…");
        },

    };
dog.randomizer();
dog.call();
dog.response();

1 个答案:

答案 0 :(得分:0)

假设您希望在致电dog.response()时收到警报或根据情况收到其他警报,但始终会收到相同的警报。

您可以通过两种方式解决该问题

更新对象

  • randomizer中,在属性中设置随机值的值并返回相同的属性。
  • response中,检查该值并显示警报。

var dog = {
        name: "Fluffy",
        leash: [true, false],

        randomizer: function() {
            this.leashed = this.leash[Math.floor(Math.random() * this.leash.length)];
            return this.leashed;
            },

        call: function() {
            alert("Honey, " + this.name + " needs to pee…");
        },

        response: function() {
            alert("Ok, i got it, dear…");
            if (!this.leashed) {
                alert("You've got to put his leash on first");
            } else alert("Enjoy your walk…");
        },

    };
dog.randomizer();
dog.call();
dog.response();

获取价值并传递价值

  • randomizer中,获取随机值并将其返回。
  • response中,传递随机值,检查该值并显示警报。

var dog = {
        name: "Fluffy",
        leash: [true, false],

        randomizer: function() {
            return this.leash[Math.floor(Math.random() * this.leash.length)];
            },

        call: function() {
            alert("Honey, " + this.name + " needs to pee…");
        },

        response: function(leashed) {
            alert("Ok, i got it, dear…");
            if (leashed) {
                alert("You've got to put his leash on first");
            } else alert("Enjoy your walk…");
        },

    };
let leash = dog.randomizer();
dog.call();
dog.response(leash);

注意,在原始代码中也有一些错误

  • randomizer中,this.leash[Math.floor(Math.random() * this.leash.length)]没有LHS
  • randomizer中,this.leash返回数组,而不是预期的某个随机值
  • response中,this.leash = false是赋值,而不是比较。为了进行比较,您将需要使用=====