gpt4 book ai didi

javascript - 为什么 Math.random 在我的代码中不起作用?

转载 作者:行者123 更新时间:2023-12-02 15:57:43 26 4
gpt4 key购买 nike

这是我的提升计划。但数学随机不起作用。

var person = {
name: "Gorg",
position: 2,
goal: 9
};
var lift = {
position: function() {
var x = Math.floor((Math.random() * 10) + 1);
}
};
console.log("Ok, buddy! You are at " + person.position + " floor");
console.log("Lift is at " + lift.position + " floor");

if (lift.position != person.position) {
console.log("Please wait a minute, lift's coming");
}
else {
console.log("Lift is here. Please enter!");
}

if (lift.position > person.position) {
for (i = person.position; i <= lift.position; i++) {
console.log(i);
}
}
else if (lift.position < person.position) {
for (i = person.position; i >= lift.position; --i) {
console.log(i);
}
}
else {
console.log("You're already at this level");
}

if (lift.position !== person.position) {
if (person.goal > person.position) {
for (i = person.position; i <= person.goal; i++) {
console.log(i);
}
}
else if (person.goal < person.position) {
for (i = person.position; i >= person.goal; --i) {
console.log(i);
}
}
else {
console.log("You're already at this level");
}
}
console.log("Congratulation! You achieve your goal!");

最佳答案

两个问题

首先,更改您的 lift.position 函数,以便它返回值(而不是将其分配给无法访问的局部变量)。

position: function() {
return Math.floor((Math.random() * 10) + 1);
}

其次,确保您调用 lift.position() 函数(使用括号调用函数)...

lift.position()

关于javascript - 为什么 Math.random 在我的代码中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31468374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com