遍历2个数组

时间:2018-12-11 06:07:10

标签: javascript html for-loop foreach

我试图遍历2个数组。第一个数组是链接名称,第二个数组是链接“ a”值。我想遍历两个数组,将第二个数组的值附加到在第一个数组中创建的每个链接的href。这就是我所拥有的,对我不起作用。

const links = ['Home', 'Contact', 'About'];
const hrefLinks = ['/', 'contact', 'about'];

for (let i = 0; i < links.length; i++) {
    for (let j = 0; j < hrefLinks.length; i++) {
        if (links.length === hrefLinks.length) {
            const li = document.createElement('li');
            const liLink = document.createElement('a');
            liLink.setAttribute('href', hrefLinks[i]);
            liLink.className = 'Test-Class';
            li.appendChild(liLink);
            li.className = 'nav-link';
            list.appendChild(li);
            li.innerHTML += links[i];
        }
    }
}

我确实可以在一个forEach循环中使用它,但是对于如何嵌套第二个forEach却感到困惑;

const links = ['Home', 'Contact', 'About'];
const hrefLinks = ['/', 'contact', 'about'];

 links.forEach(function (link) {
     const li = document.createElement('li');
     const liLink = document.createElement('a');
     li.appendChild(liLink);
     li.className = 'nav-link';
     list.appendChild(li);
     li.innerHTML += link;
 });

这是执行此操作的正确方法,还是有一种更简单/更干净的方法?

3 个答案:

答案 0 :(得分:5)

您不需要嵌套循环-您只需要将i中的第links条链接到i中的第hrefLinks条。使用forEach,您可以通过使用回调的第二个参数来实现此目的,该参数将引用正在迭代的当前索引:

const list = document.body.appendChild(document.createElement('ul'));


const links = ['Home', 'Contact', 'About'];
const hrefLinks = ['/', 'contact', 'about'];

links.forEach((linkName, i) => {
  const li = document.createElement('li');
  const a = document.createElement('a');
  a.href = hrefLinks[i];
  a.textContent = linkName;
  li.appendChild(a);
  li.className = 'nav-link';
  list.appendChild(li);
});

答案 1 :(得分:2)

创建一个包含链接名称和URL的对象数组,然后可以对该对象进行迭代以将锚点元素添加到dom中,如下所示

//an object which hold navigation url and name
var navLinks = [{
  label: 'Home',
  href: '/'
}, {
  label: 'Contact',
  href: 'contact'
}, {
  label: 'About',
  href: 'about'
}]

navLinks.forEach(function(link) {

  var li = document.createElement('li');
  li.className = 'nav-link';

  var liLink = document.createElement('a');
  var linkText = document.createTextNode(link.label);
  liLink.appendChild(linkText);
  liLink.className = 'Test-Class';
  liLink.href = link.href;

  li.appendChild(liLink);
  document.body.appendChild(li)

});

答案 2 :(得分:0)

为什么不使用除两个数组之外的对象数组?

const anchors = [
  {
    name: 'Home',
    link: '/'
  },
  {
    name: 'Contact',
    link: 'contact'
  },
  {
    name: 'About',
    link: 'about'
  }
];

let ul = document.getElementById('list');

anchors.forEach(function(item) {
  let li = document.createElement('li');
  let a = document.createElement('a');
  a.className = 'nav-link';
  a.href = item.link;
  a.innerHTML = item.name;
  li.appendChild(a);
  ul.appendChild(li);
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Anchors</title>
</head>
<body>
  <ul id="list"></ul>
</body>
</html>

我认为这很有效。

相关问题