如何獲取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
'forEach'就像一個'for'循環。你想要'地圖'。 – Blender
Thx - 我熟悉地圖 - 我應該注意到 - 抱歉 - 但我想了解爲什麼我無法在此情況下返回值的邏輯。它只是在竊聽我 - 或者我應該放棄它。 – jamie
請看這裏:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach –