简体   繁体   中英

How can I set all array elements in an element in HTML?

I have an array

    let array = [1, 2, 3];

I want all elements of this array to set on an element in HTML for example

    <p id="demo"></p>

I want the output to be 1 , 2 , 3

Last number I dont want to have comma

I tried something

       let array = [1,  2, 3]
       for(var i =0; i <=array.length;i++) {
            document.getElementById("demo").innerHTML = array[i] + "' , ";}

Thanks so much

No need to loop, use toArray or join.

 let array = [1, 2, 3]; document.getElementById("demo").textContent = array.toString(); document.getElementById("demo2").textContent = array.join(', ');
 <p id="demo"></p> <p id="demo2"></p>

If you want to loop you need to check the index and add the comma

 const array = [1, 2, 3]; let out = ''; for(let i=0; i<array.length; i++) { const comma = i == 0 ? '' : ', '; out += comma + array[i]; } document.getElementById("demo").textContent = out;
 <p id="demo"></p>

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