【问题标题】:My for loop runs only once while trying to reverse an array in javascript [closed]我的 for 循环仅在尝试在 javascript 中反转数组时运行一次 [关闭]
【发布时间】:2022-01-11 20:31:36
【问题描述】:

var amount = Number(window.prompt("number of elements"));
var list = []
for (var i = 0; i < amount; i++); {
  list.push(window.prompt("enter elements of the list"));
}
list.reverse();
document.write(list);

我试图反转一个列表,但是无论我输入多少代码,我的代码只运行一次 for 循环,询问我列表的元素并结束 for 循环并打印出我的唯一一个条目,因为 for 循环没有多次向我询问元素。我是初学者,这可能是一个愚蠢的错误,但我就是想不通。

【问题讨论】:

  • 你在for (var i = 0; i &lt; amount; i++)之后多了一个;
  • 这会创建一个空循环体,因此提示不在循环内。

标签: javascript arrays for-loop


【解决方案1】:

正如@Barmar 指出的那样,问题是由于逻辑错误造成的。

/* Read the item from the prompt until you and write it to the list container. */
function read(list, size){
  for(let i = 0 ; i < size ; ++i)
    list.push(window.prompt());
}

/* Print a list container */
function print(list){
   for(let i = 0 ; i < list.length ; ++i)
    console.log(list[i]);
}

var list = []
read(list, Number(window.prompt("number of elements")));
list.reverse();
print(list);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2019-12-19
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多