Reputation: 37
I want to iterate over an array in a synchronous manner
let arr= new Array([10,20,30]);
for(let i=0;i<arr.length;i++){
htmldata+=`<h1>${arr[i]}</h1><br/>`
}
console.log(htmldata)
What I get output is
<h1>10,20,30</h1><br/>
what I expect to store in htmldata
is (in string format)
<h1>10</h1><br/><h1>20</h1><br/><h1>30</h1><br/>
Tried from other stackoverflow answers, which gave me a way only to get the indices correctly, but not the array values
var funcs = [];
htmldata=``
for (let i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("My value: " + i,arr[i]);
htmldata+=`<h1>${arr[i]}</h1><br/>`
};
}
for(let i=0;i<3;i++) funcs[i]();
console.log(htmldata)
output:
My value: 0 [ 10, 20, 30 ]
My value: 1 undefined
My value: 2 undefined
<h1>10,20,30</h1><br/><h1>undefined</h1><br/><h1>undefined</h1><br
How to do this?
Upvotes: 0
Views: 158
Reputation: 370769
The problem is not in your iteration logic, but in your array declaration:
let arr = new Array([10, 20, 30]);
console.log(arr);
See the problem? It's an array of arrays, not an array of numbers.
There's rarely ever any reason to use use new Array
anyway. Just use an array literal alone, and you'll get what you're looking for:
let htmldata = '';
let arr= [10,20,30];
for(let i=0;i<arr.length;i++){
htmldata+=`<h1>${arr[i]}</h1><br/>`
}
console.log(htmldata)
Or, even better, use .map
.
let arr = [10,20,30];
const htmldata = arr
.map(num => `<h1>${num}</h1>`)
.join('<br>');
console.log(htmldata)
Upvotes: 1