Javascript 将array.prototype.foreach()的结果保存到未定义的变量中

Javascript 将array.prototype.foreach()的结果保存到未定义的变量中,javascript,foreach,ecmascript-5,Javascript,Foreach,Ecmascript 5,如何获取新数据,使之等于由forEach()生成的对象数组?如果我全局地定义var result=[]和console.log(result),它就会工作 forEach只是在数组中循环——它不会创建新数组。JavaScript中数组原型的map函数在数组中循环,执行回调函数中提供的逻辑,但返回一个新数组作为回调的结果。您可以在on MDN:Hey@jamie上阅读有关map函数的更多信息。您肯定应该考虑使用map()进行此操作 尽管要使用forEach(),请尝试。它通常用于模拟带有闭包的私有

如何获取新数据,使之等于由
forEach()
生成的对象数组?如果我全局地定义
var result=[]
console.log(result),它就会工作


forEach
只是在数组中循环——它不会创建新数组。JavaScript中数组原型的map函数在数组中循环,执行回调函数中提供的逻辑,但返回一个新数组作为回调的结果。您可以在on MDN:

Hey@jamie上阅读有关map函数的更多信息。您肯定应该考虑使用
map()
进行此操作

尽管要使用
forEach()
,请尝试。它通常用于模拟带有闭包的私有方法

看看这个代码

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);

下面是它的用法。

forEach
就像一个
for
循环。您需要
map
.Thx-我熟悉map-我应该注意到-抱歉-但我试图理解在这种情况下无法让它返回值的逻辑。它只是在烦我——或者我应该放弃它。看这里:@jamie:
forEach
对回调函数的返回值没有任何作用。你期望它做什么?
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);