如何让newData等于forEach()
生成的对象数组?如果我全局定义var result = []
和console.log(result);
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
答案 0 :(得分:1)
forEach
只是循环遍历数组 - 它不会创建新数组。 JavaScript中的Array原型的map函数循环遍历数组,执行您在回调函数中提供的逻辑,但返回一个给定回调的新数组,因为它的结果。您可以在MDN上阅读有关地图功能的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
答案 1 :(得分: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。