I am trying to create elements of an array dynamically and need to assign values to each array element (with the same names) and push the item to the array. I don't know how to achieve this. Please take a look at my code which I attached below. Any help is greatly appreciated. thanks.
I would like to have all elements of the array with a number value, not Lenght0, Lenght1...... The reason why I declare all the variables Length0, Length1..... and assign values to them is for testing purpose. In my application, the values are available on the screen and the script suppose to read in the values from these fields and add them to the array, then do some calculations with these values.
let Length0 = 188;
let Length1 = 54;
let Length2 = 54;
let Length3 = 312;
let Length4 = 54;
let Length5 = 54;
let Length6 = 976;
let Length7 = 54;
let Length8 = 54;
let Length9 = 169;
let Length10 = 54;
let Length11 = 54;
let Length12 = 130;
let Length13 = 57;
let Length14 = 54;
let Length15 = 260;
let Length16 = 54;
let numberOfAxles = 12;
let lengthString = '';
let Lengths = [];
let Lengths =[Length0,Length1,Length2,Length3,Length4,Length5,Length6,Length7,Length8,Length9,Length10,Length11];
document.write(Lengths+'<br><br>');
for (let i = 0; i < numberOfAxles; i++) {
lengthString = 'Length' + i;
Lengths.push('Length' + i);
//document.write(Lengths +' <br><br>');
}
//document.write('Length String: ' + lengthString + '<br>');
document.write('<br>Second: ' + Lengths + '<br>');
I am not sure I get why you want to do this, but i think this is what you are looking for:
let Length0 = 188;
let Length1 = 54;
let Length2 = 54;
let Length3 = 312;
let Length4 = 54;
let Length5 = 54;
let Length6 = 976;
let Length7 = 54;
let Length8 = 54;
let Length9 = 169;
let Length10 = 54;
let Length11 = 54;
let Length12 = 130;
let Length13 = 57;
let Length14 = 54;
let Length15 = 260;
let Length16 = 54;
let numberOfAxles = 12;
let Lengths = [];
for (let i = 0; i < numberOfAxles; i++) {
Lengths.push(eval('Length' + i));
}
console.log(Lengths);
document.write('Second: ' + Lengths.join(','));
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加