2015-10-22 42 views
1
stack_html += "<div class='co-stack-layer-title'>Application and Data" + 
         "<div class='row'>" + 
          response['Application and Data'].forEach(generateStackItem) + 
         "</div>" + 
         "</div>"; 
stack_html += "<div class='co-stack-layer-title'>Business Tools" + 
         "<div class='row'>" + 
          response['Business Tools'].forEach(generateStackItem) + 
         "</div>" + 
         "</div>"; 
stack_html += "<div class='co-stack-layer-title'>DevOps" + 
         "<div class='row'>" + 
          response['DevOps'].forEach(generateStackItem) + 
         "</div>" + 
         "</div>"; 
stack_html += "<div class='co-stack-layer-title'>Utilities" + 
         "<div class='row'>" + 
          response['Utilities'].forEach(generateStackItem) + 
         "</div>" + 
         "</div>"; 

function generateStackItem(element, index, array) { 
    var stack_item_html = ""; 
    stack_item_html += "<div class='co-service'>" + 
        "<a href='" + element['canonical_url'] + "' class='each-service hint hint--top' data-hint='" + element['name'] + "' data-align='left'>" + 
         "<img src='" + element['image_url'] + "'>" + 
        "</a>" + 
        "</div>"; 

    console.log(stack_item_html); 
    return stack_item_html;      
} 

我試圖用一個forEach迭代JavaScript對象上,似乎我不能插值的返回值到字符串相加。的Javascript的forEach返回值插值到字符串

<div class='co-stack-layer-title'>Application and Data<div class='row'>undefined</div></div><div class='co-stack-layer-title'>Business Tools<div class='row'>undefined</div></div><div class='co-stack-layer-title'>DevOps<div class='row'>undefined</div></div><div class='co-stack-layer-title'>Utilities<div class='row'>undefined</div></div> 
+0

您使用的回覆如何?你想用generateStackItem做什麼? – Danmoreng

回答

4

forEach返回undefined。使用map + join

"abc" + response['Utilities'].map(generateStackItem).join("") + "def"; 
+0

真棒謝謝 –

+0

map + join = [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce),稍微調整一下回調。 – James

+0

map + join!= reduce。在加入的情況下,你可以將你的作品合適地粘合在一起,減少難度。儘管這裏並不重要。 – Halcyon

0

當您的數組是空的,forEach函數將返回undefined,e.g.you會得到一個undefined當你調用forEach這樣[].forEach(generateStackItem),因此請確保response['Application and Data']是一個空數組。