简体   繁体   中英

Return value from “loop” for two dimensional array

I have an array.

 var citycode = [ ["In Milan", 0], ["Rom", 5], ["Modena", 6], ["Others", 20] ]; 

How can I return value from For loop for this Array to have:

<div class="loop"><span>In Milan</span><span>0</span> </div>
<div class="loop"><span>Rom</span><span>5</span> </div>
....

Thank you very much.

Using functional programming, without loops.

 var cityCode = [ ["In Milan", 0], ["Rom", 5], ["Modena", 6], ["Others", 20] ]; const result = cityCode.map(code => `<div class="loop"><span>${code[0]}</span><span>${code[1]}</span></div>` ).join('') document.body.innerHTML = result; console.log(result); 

 var citycode = [ ["In Milan", 0], ["Rom", 5], ["Modena", 6], ["Others", 20] ]; for (var i = 0; i < citycode.length; i++) { for (var o = 0; o < citycode[i].length; o++) { console.log(citycode[i][o]) } } 

Use 2 for loop to get each item

You could create DOM elements and append body .

 var citycode = [["In Milan", 0], ["Rom", 5], ["Modena", 6], ["Others", 20]]; citycode.forEach(function (city) { var div = document.createElement('div'); city.forEach(function (a) { var span = document.createElement('span'); span.appendChild(document.createTextNode(a)); this.appendChild(span); }, div); this.appendChild(div); }, document.body); 

Not to be pedantic but OP asked for for loop..

    var htmlContent = "";
            for (var i = 0; citycode.length > i; i++) {
              htmlContent += '<div class="loop"><span>' + citycode[i][0] + '</span><span>' + citycode[i][1] + '</span></div>'
    }

I guess Array.prototype.reduce() is ideal for these jobs. You may do functionally as follows;

You are basically expected not to work on DOM but on a document fragment and once finished with your job to append the document fragment to the correct place at the DOM all at once.

 var citycode = [["In Milan ", 0], ["Rom ", 5], ["Modena ", 6], ["Others ", 20]], mainDiv = document.getElementById("main"); mainDiv.appendChild(citycode.reduce(function(p,c){ var d = document.createElement("div"); d.classList.add("loop"); c.reduce(function(dv,sp){ var s = document.createElement("span"); s.textContent = sp; dv.appendChild(s); return dv; },d); p.appendChild(d); return p; },document.createDocumentFragment())); 
 .loop {color: red} 
 <div id="main"></div> 

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