0

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?

2
  • 1
    your array contains 1 item, which is an array of 3 items. What do you expect this new Array([10,20,30]); to do? Commented Apr 10, 2021 at 21:50
  • @njzk22 Oh yes, Thank you, I was too dumb to make that silly mistake Commented Apr 10, 2021 at 21:53

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.