For循环返回数组值

时间:2017-02-15 10:42:49

标签: arrays for-loop return-value mustache

我正在尝试通过胡子模板插入菜单的网址。但只是为数组返回了第一个值。

或者这是错误的返回方法

      var main_menu_link =  ["main_dashboard.html", "#", "online_dashboard.html","index.html","#","#","#"]; 
      var url = "";
      var i;
      var url_link="";
      for(i = 0; i < main_menu_link.length; i++) {
       url += main_menu_link[i];
       return '<a href="'+ url  +'">' + text + '</a>';   
     }

CodePen working here

2 个答案:

答案 0 :(得分:0)

return语句必须在循环之后:

var main_menu_link =  ["main_dashboard.html", "#", "online_dashboard.html","index.html","#","#","#"]; 
var url = "";
var i;
var url_link="";
for(i = 0; i < main_menu_link.length; i++) {
  url += '<a href="'+ main_menu_link[i] +'">' + text + '</a>';  
}
return url; 

答案 1 :(得分:0)

如下所示,正确的模板可以用于其他人

var link_details = { "link_details" :[ 
{ main_menu: "Dashboard", main_menu_link: "dashboard.html" }, 
{ main_menu: "Analytics", main_menu_link: "#" }, 
{ main_menu: "System", main_menu_link: "system.html" } 
]}; 

var template = "<ul>{{#link_details}}<li><a href =\" {{main_menu_link}}\">{{main_menu}}</a></li>{{/link_details}}‌​</ul>"; 
var html = Mustache.to_html(template, link_details); 
document.write(html)