您好,我正在尝试在两个函数的输出之间获取一个随机整数,我的示例如下,我没有收到错误,但它不起作用。
function getRndInteger(...args) {
const [low, high] = [Math.min(...args), Math.max(...args)];
return Math.floor(Math.random() * (high - low)) + low + 103;
}
function age(h){
var h = prompt ("How old are you?");
return h;
}
function videogames(i){
var i = prompt ("How many hours of video games have you played last month?");
return i;
}
document.write (getRndInteger(age(h),videogames(i)));
我必须用这种方式写出来,因为年龄和视频游戏部分必须采用函数形式,这可能吗?
答案 0 :(得分:3)
我看到的问题是,您要向函数传递参数,然后重新定义不需要的变量。您可以删除将值传递给函数的操作,然后像现在一样返回值。
注意:您可能想要像下面那样将提示值转换为整数,因为提示会返回字符串。
function getRndInteger(...args) {
const [low, high] = [Math.min(...args), Math.max(...args)];
return Math.floor(Math.random() * (high - low)) + low + 103;
}
function age() {
var h = prompt("How old are you?");
return parseInt(h);
}
function videogames() {
var i = prompt("How many hours of video games have you played last month?");
return parseInt(i);
}
document.write(getRndInteger(age(), videogames()));
答案 1 :(得分:1)
呼叫age(h),videogames(i)
时,任何地方都没有声明h
或i
。因此,将其删除为参数
function getRndInteger(...args) {
const [low, high] = [Math.min(...args), Math.max(...args)];
console.log(low, high)
return Math.floor(Math.random() * (high - low)) + low + 103;
}
function age() {
var h = prompt("How old are you?");
return h;
}
function videogames() {
var i = prompt("How many hours of video games have you played last month?");
return i;
}
document.write(getRndInteger(age(), videogames()));