我是初学程序员,我想做这项工作,但事实并非如此。你能帮我解释一下是什么问题吗?例如,如果我输入20岁以下,我希望它能告诉我走多长时间走到我选择的任何星球。其中大部分是弄清楚如何让代码存储用户选择的任何选项,然后将其应用于年龄并使用数据来计算它。谢谢!
<legend>basic info</legend>
<p> What is your destination?
<select onchange = "selectDestination(this.value)">
<option value="mercury">Mercury</option>
<option value="venus">Venus</option>
<option value="mars">Mars</option>
<option value="jupiter">Jupiter</option>
<option value="saturn">Saturn</option>
<option value="uranus">Uranus</option>
<option value="neptune">Neptune</option>
<option value="pluto">Pluto</option>
</select>
<script type="text/javascript">
var planets = new Array();
planets['mercury'] = 48000000;
planets['venus']=25000000
planets['mars']=25000000
planets['jupiter']=33900000
planets['saturn']=365000000
planets['uranus']=1200000000
planets['neptune']=2600000000
planets['pluto']=2800000000
function selectDestination(selectedValue) {
window.alert(selectedValue + " distance=" + planets[selectedValue]);
}
</script>
</p>
<p>
<label>how old are you?</label>
<form id="form" onsubmit="return false;">
<input type="number" id="userInput">
<input type="submit" onclick="age()">
</form>
<script type="text/javascript">
function age()
{
var input = document.getElementById("userInput");
alert(input);
}
if(age<20);
{
alert("YOU ARE UNDER 20");
var runSpeed=6.3;
var walkSpeed=2.1
var water = 1.5;
var calories = 2500;
var runTime = planets[selectedValue]/runSpeed;
var runDays = runTime/24
document.write("it will take "+runTime+" hours and "+runDays+" days to make it to"+selectedValue);
}
if(21<age>45) {
alert("YOU ARE AT YOUR PHYSICAL PEAK");
var runSpeed=8.3;
var walkSpeed=3.1;
var water = 2;
var calories = 3000;
var runTime = planets[selectedValue]/runSpeed;
var runDays = runTime/24;
document.write("it will take "+runTime"hours and"+runDays+"days to make it to"+selectedValue);
}
if(age<45){
alert("YOU ARE PROBABLY TOO OLD TO TAKE THIS TRIP");
var runSpeed=5.3;
var walkSpeed=1.1;
var water=1.5;
var calories=3000;
var runTime = planets[selectedValue]/runSpeed;
var rundays = planets[selectedValue]/24;
document.write("it will take "+runTime"hours and"+runDays+"days to make it to"+selectedValue);
}
</script>
</p>
答案 0 :(得分:3)
此处的代码不起作用。
var planets = new Array();
planets['mercury'] = 48000000;
planets['venus']=25000000
planets['mars']=25000000
planets['jupiter']=33900000
planets['saturn']=365000000
planets['uranus']=1200000000
planets['neptune']=2600000000
planets['pluto']=2800000000
您要声明的是一个数组,您想要推送的是对象。
你最理想的行星是var planets = [ {planet: 'mercury', distance: 48000000}, {planet: 'venus', distance: 25000000 }, ... ]
现在,没有任何事情发生,因为你的语法正在寻找一个密钥为mercury
或venus
而没有找到任何东西的对象。
接下来你要做的就是console.log()
无论用户输入什么年龄。确保您的函数age()
接受参数,因此它看起来更像age(val)
一旦您console.log()
记录了用户输入的年龄,您应该非常接近。在此之后你所要做的就是抓住用户选择的行星,你可以通过循环遍历planets
数组并将用户选择的内容与数组中的内容进行匹配来实现。像planets.filter(planet => planet.indexOf(planetUserSelected) !== -1)
这样的东西可以让你找回你正在寻找的对象,你可以console.log()
那个价值并从那里开始。