简体   繁体   English

如何使用JavaScript创建多个随机段落元素?

[英]How i can create multiple random paragraph elements with javascript?

I am trying to create multiple paragraphs with random text using the values in this array: 我正在尝试使用此数组中的值创建带有随机文本的多个段落:

var values = ["Carl","Maria","Joseph","Tatiane","Dayanne"];

But honestly I do not know how to do that; 但老实说,我不知道该怎么做。 this is my code... 这是我的代码...

var paragraph = document.createElement("p");
paragraph.innerText = "random string";
document.body.appendChild(paragraph);

I need to create 35 paragraphs ... 我需要创建35个段落...

innerText is a quirky nonstandard property that IE introduced. innerText是IE引入的古怪的非标准属性。 It is highly recommended to instead use the standard, quicker, more reliable textContent instead - see http://perfectionkills.com/the-poor-misunderstood-innerText 强烈建议改用标准,更快,更可靠的textContent代替-请参见http://perfectionkills.com/the-poor-misunderstood-innerText

You can get a random element from an array using arr[Math.floor(Math.random() * arr.length)] : 您可以使用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; }); 

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM