![](/img/trans.png)
[英]How can I select multiple html elements of an array and set them all to a function at once?
[英]How can I set all array elements in an element in HTML?
我有一個數組
let array = [1, 2, 3];
例如,我希望此數組的所有元素都設置在 HTML 中的元素上
<p id="demo"></p>
我希望輸出為 1 , 2 , 3
最后一個數字我不想有逗號
我嘗試了一些東西
let array = [1, 2, 3]
for(var i =0; i <=array.length;i++) {
document.getElementById("demo").innerHTML = array[i] + "' , ";}
非常感謝
無需循環,使用 toArray 或 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>
如果要循環,則需要檢查索引並添加逗號
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.