简体   繁体   中英

Need help iterating over an array In Javascript

I'm currently struggling with the following problem:

  1. Create an <a> element,
  2. On the new element add an href attribute and its value set to the href property of the "link" object. edit: adding this.. Set the new element's content to the value of the textproperty of the "link" object.
  3. Append the new element to the "topMenu" element. goal i want to achieve: making 'About' 'Catalog' 'Orders' 'account' into links. (im new to javascript)

Here my code:

 var menuLinks = [{ text: 'about', href: '/about' }, { text: 'catalog', href: '/catalog' }, { text: 'orders', href: '/orders' }, { text: 'account', href: '/account' }, ]; var links = document.createElement('a'); menuLinks.map(function(links) { return '<li>' + links + '</li>'; document.getElementById("mylinks").href = "menuLinks";

You can try this.

 var menuLinks = [{ text: 'about', href: '/about' }, { text: 'catalog', href: '/catalog' }, { text: 'orders', href: '/orders' }, { text: 'account', href: '/account' }, ]; let menuAnch=menuLinks.map(r=>`<li> <a href='${r.href}'>${r.text} </a> </li>`).join(""); document.getElementById("mylinks").innerHTML=menuAnch; console.log(menuAnch);
 <div id="mylinks"></div>

Your question is a little confusing but I think what you're trying to achieve is something like this:

 var menuLinks = [{ text: 'about', href: '/about' }, { text: 'catalog', href: '/catalog' }, { text: 'orders', href: '/orders' }, { text: 'account', href: '/account' }, ]; var links = menuLinks.map(link => `<a href='${link.href}'>${link.text}</a>`); console.log(links);

Resulting array:

[
  "<a href='/about'>about</a>",
  "<a href='/catalog'>catalog</a>",
  "<a href='/orders'>orders</a>",
  "<a href='/account'>account</a>"
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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