Count vector elements and put links on the page

3

I want to make a script that counts how many vector indexes 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> 


Getting this on the page:


1 2 3 4 5


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

    
asked by anonymous 31.12.2016 / 15:04

1 answer

5

See if this works:

Use a .map() , it's a function of the array, 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 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>")
    
31.12.2016 / 15:13