繁体   English   中英

当我尝试从提示框中获取用户输入并在数组中显示这些输入值时,我收到重复的输入值作为 Output

[英]I am getting repeated input values as an Output when I am trying to get User Input from Prompt box and showing those input values in an Array

例如 - 1 我得到了从提示框中输入的所有值。

//示例 - 1

 document.getElementById("btn").onclick = () => { let cars = new Array(5); for(let get = 0; get <= 5; get++){ cars[get] = prompt("Enter Any Values"); } for(let show = 0; show <= 5; show++ ){ document.getElementById("data1").innerHTML += `You have Entered: ${cars[show]}<br>`; } document.getElementById("data2").innerHTML = `The Total Values are: ${cars}`; }
 <button id="btn">Click Here</button> <div id="data1"></div> <div id="data2"></div>

我在示例中遇到问题 - 2.请告诉我哪里做错了。 谢谢你..!

//示例 - 2

 document.getElementById("btn").onclick = () => { let cars = new Array(5); for(let get of cars){ cars[get] = prompt("Enter Any Values"); } for(let show of cars){ document.getElementById("data1").innerHTML += `You have Entered: ${cars[show]}<br>`; } document.getElementById("data2").innerHTML = `The Total Values are: ${cars}`; }
 <button id="btn">Click Here</button> <div id="data1"></div> <div id="data2"></div>

for of用于对象的数组值(而不是它们的索引)。 MDN 网站

您将for in用于索引:

 const array1 = ['a', 'b', 'c']; for (const element of array1) { console.log(element); } for (const element in array1) { console.log(element); }

现在回答第二个代码中发生的事情:

get每次在循环内都是undefined的,因为cars数组是空的。 所以没有价值观。 每次在您的循环中都会发生这种情况:

cars[undefined] = (your prompt answer)

而且汽车[未定义]的价值也被覆盖了

此时, cars是一个 object ,其键undefined ,值为YOURLASTENTEREDVALUE 稍后for of循环再次在cars数组上运行以显示值。 现在再次show在循环内undefined因为cars仍然是空的。

所以每次你再次做cars[undefined] 但是这次你有一个值,这将是你回答的最后一个值,并且正在显示。

 document.getElementById("btn").onclick = () => { let cars = new Array(3); for(let get of cars){ console.log(get); cars[get] = prompt("Enter Any Values"); } console.log(Object.keys(cars)); console.log(Object.values(cars)); console.log(cars[undefined]); for(let show of cars){ console.log(show); document.getElementById("data1").innerHTML += `You have Entered: ${cars[show]}<br>`; } document.getElementById("data2").innerHTML = `The Total Values are: ${cars}`; }
 <button id="btn">Click Here</button> <div id="data1"></div> <div id="data2"></div>

编辑根据 OP 的要求,修复它的一种方法:

 document.getElementById("btn").onclick = () => { let cars = new Array(3).fill(0); for(let get in cars){ cars[get] = prompt("Enter Any Values"); } for(let show in cars){ document.getElementById("data1").innerHTML += `You have Entered: ${cars[show]}<br>`; } document.getElementById("data2").innerHTML = `The Total Values are: ${cars}`; }
 <button id="btn">Click Here</button> <div id="data1"></div> <div id="data2"></div>

最初使用默认0填充数组,以便可以使用for in对其进行迭代,这是一种方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM