用多维数组填充标题 [英] Populate header with multi dimensional array

查看:70
本文介绍了用多维数组填充标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中有这个多维数组,我正在尝试使用它填充HTML中的标题我想填充此标题,以便所有名字在标题中单独打印出来。有没有一个简单的方法来实现这个cos我不知道如何去做。任何帮助将不胜感激。



我尝试过:



这是我的JSfiddle [ ^ ]

I have this multi-dimensional array in JavaScript and i'm trying to populate a header in HTML with it i want to populate this header so that all the first name is printed out separately in the header. Is there an easy way to accomplish this cos i'm not sure how to go about it. Any help would be greatly appreciated.

What I have tried:

Here is my JSfiddle[^]

推荐答案

有几种方法可以解决这个问题,但许多快捷方式会产生意想不到的副作用。干净利落的最佳方法是创建您想要填充的元素,并将它们附加到您感兴趣的DOM中。例如:



There are a few ways to approach this, but many of the "shortcuts" will have unintended secondary effects. The best way to do this cleanly is to create the elements that you want to populate and append them into the DOM at your point of interest. For example:

<html>
<head>
    <script type="text/javascript">
        let personArr = [
            {firstName:"John", lastName:"Doe", age:21},
            {firstName:"Paul", lastName:"Logan", age:22},
            {firstName:"Sean", lastName:"Kim", age:32},
            {firstName:"Ken", lastName:"Chow", age:12}
        ];

        let peopleDiv = document.getElementById('People');

        for(let i=0;i<personArr.length;i++){
            let newElement = document.createElement('h6');
            newElement.innerHTML = personArr[i].firstName;
            peopleDiv.appendChild(newElement);
        }
    </script>
</head>
<body>
<div id="People"></div>
</body>
</html>





如果您需要使用多维数组执行此操作,可以从嵌套循环中进行DOM分配。



if you need to do this with a multi-dimensional array you can make your DOM assignments from a nested loop.


这篇关于用多维数组填充标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆