[英]How to get all values from a javascript array and print in a paragraph tag
Please any assistance will be highly appreciated 请任何帮助将不胜感激
var array = ["text1", "text2"];
for(var i = 0; i < array.length; i++) {
document.getElementById("printarray").innerHTML = array[i]; // line 1
Console.log(array[i]); // line 2
}
Line 1 prints only the last text in the array. 第1行仅打印数组中的最后一个文本。
Line 2 prints all texts 第2行会列印所有文字
Why is this so cause I want to print all data in printarray which is a <p>
为什么会这样,原因是我要打印所有位于
<p>
printarray中的数据
You need to use +=
to append the new data to innerHTML
rather than overwriting it each time as you are currently doing with =
. 您需要使用
+=
追加新数据innerHTML
,而不是每次都覆盖它,你正在与做=
。
var array = ["text1", "text2"];
for(var i = 0; i < array.length; i++) {
document.getElementById("printarray").innerHTML += array[i];
}
You can also add a line break with <br>
to put each element on a new line to make things more readable. 您还可以在
<br>
添加换行符,以将每个元素放在换行符上,以使内容更具可读性。
var array = ["text1", "text2"];
for(var i = 0; i < array.length; i++) {
document.getElementById("printarray").innerHTML += array[i] + "<br>";
}
The way you were doing it, the innerHTML
gets re-written to contain only one array element every time the loop runs. 这样做的方式是,每次循环运行时,都将
innerHTML
重写为仅包含一个数组元素。
You could build up a string that contains all of the values within the array, and then set the innerHTML
to that string. 您可以构建一个包含数组中所有值的字符串,然后将
innerHTML
设置为该字符串。 This would override whatever was in that HTML element - replacing it with all of the elements in the array. 这将覆盖该HTML元素中的所有内容-将其替换为数组中的所有元素。
var array = ["text1", "text2"];
var temp = "";
for(var i= 0; i < array.length; i++) {
temp += array[i];
}
document.getElementById("printarray").innerHTML = temp;
Alternatively, you can ADD each string to the innerHTML
, which would concatenate every string in array onto whatever is already in the HTML element. 或者,您可以将每个字符串添加到
innerHTML
,这会将数组中的每个字符串连接到HTML元素中已有的任何字符串上。
var array = ["text1", "text2"];
for(var i= 0; i < array.length; i++) {
document.getElementById("printarray").innerHTML += array[i];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.