![](/img/trans.png)
[英]In my javascript function I am trying to get the values from a form user input to a function I created and the output the answer
[英]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.