js循环数组创建dom元素,并补零

padStart() 只针对字符串,padEnd向后补零 innerHtml创建dom元素

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <style>
        li {
            list-style: none;
            color: aquamarine;
        }

        li:nth-child(2n) {
            color: blueviolet;
        }
    </style>

    <body>
        <ul id="list"></ul>
    </body>
    <script type="text/javascript">
        var perArr = []
        // 遍历循环数组
        for (var i = 0; i < 20; i++) {
            console.log(i);
            if (i % 2 == 0) {
                perArr.push({
                    id: i,
                    name: "大幂幂",
                    age: i + 10
                }, )
            } else {
                perArr.push({
                    id: i,
                    name: "蔡文姬",
                    age: i + 10
                }, )
            }

        }
        // 定义人员列表的html字符串
        let htmlStr = ''
        // 用数据生成人员列表
        perArr.forEach(item => {
            htmlStr += `<li>${item.name}-${item.age}------${(item.id+1).toString().padStart(3, "0")}</li>`

            console.log((item.id+1).toString().padEnd(3, "0"));
        })
        // 操作dom呈现界面
        document.getElementById('list').innerHTML = htmlStr
    </script>

</html>

 

posted @ 2021-08-10 09:05  橘雎  阅读(1009)  评论(0编辑  收藏  举报