我想要做的是让用户键入一个数字,并根据他们键入的数字显示数组中的相应元素,但使用while循环并连接循环的结果。我尝试创建一个while循环,当变量大于或等于最小数组值时运行。但是我在尝试使所有这些事情发挥作用时遇到了很多问题。
Name: <input type="text" id="myText" value="Mickey">
<p id="demo"></p>
<p>Click the button to change the value of the text field.</p>
function myFunction() {
var x = document.getElementById("myText");
var currentVal = x.value;
var jobs = ["Best Buy", "Staples", "Macys", "Dunkin Donuts", "Legal Aid"];
var i = jobs.length - 1;
while (jobs.length >= i) {
document.getElementById("demo").innerHTML = jobs[i] + " ";
break;
}
}
答案 0 :(得分:4)
public static double getBMIMetric()
{
Scanner input = new Scanner(System.in);
// Input Weight
System.out.print("Enter your weight in kilograms: ");
int weightKG = input.nextDouble();
System.out.print("Enter your height in centimeters: ");
int heightCM = input.nextInt();
System.out.println();
return weightKG/Math.pow(heightCM/100.0, 2);
}
public static void calculateMetricBMI()
{
System.out.println("A body mass index of 20-25 is considered \"normal\"");
double bmiMetric = getBMIMetric();
System.out.print("Your BMI is " + bmiMetric);
}
&#13;
var input = document.getElementById("myText");
var demo = document.getElementById("demo");
var jobs = ["Best Buy","Staples","Macys","Dunkin Donuts","Legal Aid"];
function myFunction() {
// Get val from array or fallback to empty String
demo.innerHTML = jobs[this.value] || "";
}
input.addEventListener("input", myFunction);
&#13;
如果您希望用户输入要返回的项目数(从第一个数组键开始):
"What I want to do is have the user type a number
and based on the number they type it displays
the corresponding element"<br>
Type your Number: <input type="text" id="myText" value="">
<p id="demo"></p>
&#13;
var input = document.getElementById("myText");
var demo = document.getElementById("demo");
var jobs = ["Best Buy","Staples","Macys","Dunkin Donuts","Legal Aid"];
function myFunction() {
// Get val from array or fallback to empty String
demo.innerHTML = jobs.slice(0, this.value).join("<br>");
}
input.addEventListener("input", myFunction);
&#13;
答案 1 :(得分:0)
我想要做的是让用户键入一个数字并基于 它们键入的数字显示数组中的相应元素 但是使用while循环并连接循环的结果。
尝试用input type="number"
元素替换input type="text"
元素; onchange
事件;用+=
运算符替换while
循环以将.innerHTML
元素与id
demo
连接起来,Array.prototype.splice()
Name:
<input type="number" min="0" max="4" id="myText" value="Mickey">
<p id="demo"></p>
<p>Click the button to change the value of the text field.</p>
<script>
var x = document.getElementById("myText"),
demo = document.getElementById("demo"),
jobs = ["Best Buy", "Staples", "Macys", "Dunkin Donuts", "Legal Aid"];
function myFunction() {
var val = jobs.splice(this.value, 1);
demo.innerHTML += val + " ";
}
x.onchange = myFunction; x.focus();
</script>
&#13;