我正在尝试使用此数组中的值创建带有随机文本的多个段落:
var values = ["Carl","Maria","Joseph","Tatiane","Dayanne"];
但说实话,我不知道该怎么做;这是我的代码......
var paragraph = document.createElement("p");
paragraph.innerText = "random string";
document.body.appendChild(paragraph);
我需要创建35个段落......
答案 0 :(得分:0)
innerText是IE推出的一种古怪的非标准属性。强烈建议改为使用标准,更快,更可靠的textContent - 请参阅http://perfectionkills.com/the-poor-misunderstood-innerText
您可以使用arr[Math.floor(Math.random() * arr.length)]
从数组中获取随机元素:
const words = ["Carl","Maria","Joseph","Tatiane","Dayanne"];
Array.from({ length: 35 })
.forEach(() => {
const randomText = words[Math.floor(Math.random() * words.length)];
document.body
.appendChild(document.createElement("p"))
.textContent = randomText;
});
答案 1 :(得分:0)
<script>
var values = ["Carl", "Maria", "Joseph", "Tatiane", "Dayanne"];
var total = 35;
for (count = 1; count <= total; count++) {
// Get random index within the array bounds
var randomIndex = Math.floor(Math.random() * values.length);
// Get value in the array that corresponds to the random index.
var value = values[randomIndex];
// Create the <p> tag.
var p = document.createElement('p');
p.innerText = value;
document.body.appendChild(p);
}
</script>