简体   繁体   中英

How can I change an array in Javascript?

I want to convert numbers (inputted by user) into an array. These are the inputs:

<input id="x1_y1" class="v x1 y1">
<input id="x2_y1" class="v x2 y1">
<input id="x3_y1" class="v x3 y1">
<input id="x4_y1" class="v x4 y1">
<input id="x5_y1" class="v x5 y1">
<input id="x6_y1" class="v x6 y1">
<input id="x7_y1" class="v x7 y1">
<input id="x8_y1" class="v x8 y1">
<input id="x9_y1" class="v x9 y1">

<input id="x1_y2" class="v x1 y2">
<input id="x2_y2" class="v x2 y2">
<input id="x3_y2" class="v x3 y2">
<input id="x4_y2" class="v x4 y2">
<input id="x5_y2" class="v x5 y2">
<input id="x6_y2" class="v x6 y2">
<input id="x7_y2" class="v x7 y2">
<input id="x8_y2" class="v x8 y2">
<input id="x9_y2" class="v x9 y2">

<input id="x1_y3" class="v x1 y3">
<input id="x2_y3" class="v x2 y3">
<input id="x3_y3" class="v x3 y3">
<!-- etc.... -->

Of who I have stored the ids in javascript.

h1 = ["x1_y1","x2_y1","x3_y1","x1_y2","x2_y2","x3_y2","x1_y3","x2_y3","x3_y3"];
h2 = ["x4_y1","x5_y1","x6_y1","x4_y2","x5_y2","x6_y2","x4_y3","x5_y3","x6_y3"];
h3 = ["x7_y1","x8_y1","x9_y1","x7_y2","x8_y2","x9_y2","x7_y3","x8_y3","x9_y3"];
h4 = ["x1_y4","x2_y4","x3_y4","x1_y5","x2_y5","x3_y5","x1_y6","x2_y6","x3_y6"];
h5 = ["x4_y4","x5_y4","x6_y4","x4_y5","x5_y5","x6_y5","x4_y6","x5_y6","x6_y6"];
// etc....

I also got these empty arrays to store the inputted numbers:

valueH1=["","","","","","","","",""];
valueH2=["","","","","","","","",""];
valueH3=["","","","","","","","",""];
valueH4=["","","","","","","","",""];
valueH5=["","","","","","","","",""];
// etc....

Then I use the ids in the first arrays to get the numbers I want to place in the second.

for(i=0;i<9;i++){
    var oldStr = "h1["+i+"]";
    eval("valueH1["+i+"]") = document.getElementById(eval(oldStr)).value;
};
alert(valueH1.join('\n'));

But this doesn't work. What is going wrong or is there a way easier solution?

You don't need eval and you might need to do a bit of studying on how to optimize your programming logic...but just to get your current code working, you would do something like.

for(i=0;i<9;i++){
  var oldStr = h1[i];
  valueH1[i] = document.getElementById(oldStr).value;
};
alert(valueH1.join('\n'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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