2014-02-15 57 views
2

如何獲取newData等於由forEach()生成的對象數組?它的工作原理,如果我定義var result = []全球和console.log(result);將array.protoype.foreEach()的結果保存到未定義的變量中

var paragraphs = ["this is a p", "%%this is an h2", "%this is an h1"]; 

var newData = paragraphs.forEach(function(x) { 
    var result = []; 
    var header = 0; 
    while (x.charAt(header) === "%") 
    header++; 

    if (header > 0) { 
     result.push({type:"h" + header, content: x.slice(header)}); 
    } else { 
     result.push({type: "p", content: x}); 
    } 
     return result; 

}); 

console.log(newData); // undefined 
+2

'forEach'就像一個'for'循環。你想要'地圖'。 – Blender

+0

Thx - 我熟悉地圖 - 我應該注意到 - 抱歉 - 但我想了解爲什麼我無法在此情況下返回值的邏輯。它只是在竊聽我 - 或者我應該放棄它。 – jamie

+0

請看這裏:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach –

回答

0

嘿@jamie您絕對應該想到使用map()進行此操作。

雖然如果要使用forEach(),請嘗試Immediately-Invoked Function Expression。它通常用於模擬具有閉包的私有方法。

這段代碼

var paragraphs = ["this is a p", "%%this is an h2", "%this is an h1"]; 

/* Using Immediately-Invoked Function Expression */ 
var newData = (function() { 
    var result = [] 
    paragraphs.forEach(function (x) { 
     var header = 0; 
     while (x.charAt(header) === "%") 
      header++; 

     if (header > 0) { 
      result.push({type: "h" + header, content: x.slice(header)}); 
     } else { 
      result.push({type: "p", content: x}); 
     } 
    }); 
    return result; 
})(); 

console.log(newData); 

/* Using Map */ 

var newestData = paragraphs.map(function (x) { 
    var header = 0; 
    while (x.charAt(header) === "%") 
     header++; 

    if (header > 0) { 
     x = {type: "h" + header, content: x.slice(header)}; 
    } else { 
     x = {type: "p", content: x}; 
    } 
    return x; 
}); 

console.log(newestData); 

看一看這裏的jsfiddle它。

相關問題