我需要创建一个=
,要求用户输入5个值。
他们必须输入城市名称(字符串),我需要使用Array
循环创建它。
然后我需要使用另一个for
循环输出该信息。
这是我到目前为止所做的:
for
我不知道在//Declare the variables
var cities= array(SIZE);
var SIZE = 5;
var index = 0;
var BR = "<br />";
// Create the for loop to prompt the user
for(index = 0; index < SIZE ; index++) {
cities= prompt("Please enter the cities!");
}
//Output the array information
for( /* ? */ ) {
document.write(cities[SIZE]+ " was the city you entered" + BR);
}
之间放置什么来输出该信息。有更好的方法吗?
答案 0 :(得分:0)
主要问题是你没有添加到cities
- 每次循环时你都用字符串替换数组。您想要使用push()
。
并且不输出cities[SIZE]
- 将超过数组的末尾。循环(就像输入一样)并输出cities[index]
。
//Declare the variables
var SIZE = 5;
var cities = new Array(SIZE); // JS is case-sensitive
var index = 0;
var BR = "<br />";
//Create the for loop to prompt the user
for (index = 0; index < SIZE; index++) {
cities[index] = prompt("Please enter the cities!");
}
//Output the array information
for (index = 0; index < SIZE; index++) {
document.write(cities[index] + " was the city you entered" + BR);
}
答案 1 :(得分:0)
//Declare the variables
var size = 5,
cities = [];
//Create the for loop to prompt the user
for (var index = 0; index < size; index++) {
cities.push(prompt("Please enter the cities!"));
}
//Output the array information
for (var index in cities) {
document.write(cities[index] + " was the city you entered <br />");
}