【问题标题】:forEach store output into variable and access outside anonymous functionforEach 将输出存储到变量中并在匿名函数之外访问
【发布时间】:2017-02-22 12:37:55
【问题描述】:

我有这样一段代码:

tg.router._routes.forEach(function(entry){
console.log(entry._commands[0]._textPattern)
});

因为在对象(entry._commands[0]._textPattern)里面是三项,console.log会被调用3次。

如何将“entry._commands[0]._textPattern”存储到变量(可以是数组)中,然后在匿名函数之外使用该变量?

我需要一个不同的变体,因为我不想稍后将 forEach 的输出一次全部传递给处理程序。

【问题讨论】:

    标签: javascript foreach ecmascript-6


    【解决方案1】:

    你可以试试map:

    const something = tg.router._routes.map(entry => entry._commands[0]._textPattern);
    

    【讨论】:

    • 如图所示,这完全不会做任何事情......当然应该在该代码之前有一个var something =:p
    • 真;添加const,因为有一个ES6标签:)
    • 有人会解释我的解决方案和这个解决方案有什么区别?为什么它假装比我的解决方案更好?
    • 对于像这样的简单任务,我通常更喜欢 map,因为它简洁、易读且不需要本地状态。
    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 2020-08-19
    • 2019-05-11
    • 1970-01-01
    • 2015-08-08
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多