Count vector elements and place links on the page

Asked

Viewed 261 times

3

I want to make a script which counts how many vector tiles I have inside new Array.

Example

var array = new Array('001.html', '002.html', '003.html', '004.html', '005.html')


.. and add them in the HTML document, right in the body body, something like:

<a href="001.html">1</a> 

<a href="002.html">2</a> 

<a href="003.html">3</a> 

<a href="004.html">4</a> 

<a href="005.html">5</a> 


Staying like this on the page:


1 2 3 4 5


I just need tips and/or small examples of how to achieve this.

  • a foreach would not solve?

  • @diegofm So I’m trying to create something with loop for

1 answer

5


See if this works:

Use a .map(), is an array function, similar to .forEach(), with the difference that the return of the function to each loop is what will replace the corresponding element in the source array.

var array = new Array('001.html', '002.html', '003.html', '004.html', '005.html')

var html = array.map(function(link, index){
  return "<a href="+ link +" >" + (index+1) + "</a>";  
})

document.body.innerHTML = html.join("<br>")

Version with the for:

var array = new Array('001.html', '002.html', '003.html', '004.html', '005.html')

var html = [];

for(var i = 0; i < array.length; i++){
  html[i] = "<a href="+ array[i] +" >" + (i+1) + "</a>";  
}

document.body.innerHTML = html.join("<br>")

  • Really very good at what I need. But first I wish to know one thing - in this passage array.map would run on obsolete browsers. Excuse my ignorance, but I’ve never seen you

  • @Diegohenrique, wheel yes, you can see its compatibility here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Browser_compatibility

  • My God! Watch us think we learned everything. I’ve never seen it before array.map. This is new I will try to study more on the subject.

  • @Diegohenrique, see more about array here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array :)

  • Thanks!!! I knew there was more than one way to do the same thing, it is good to always have this in mind. It was even better I understand the whole logic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.