//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();
答案 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
是赋值,而不是比较。为了进行比较,您将需要使用==
或===