简体   繁体   English

JavaScript forEach 循环中的回调/函数作用域

[英]Callback/function scope in a forEach loop in JavaScript

I discovered dōmo from Jed Schmidt which seems useful for creating server side HTML in node.js.我从 Jed Schmidt 发现了dōmo ,它对于在 node.js 中创建服务器端 HTML 似乎很有用。

Basic stuff works but I lack to see how I can use loops like forEach() on arrays to create things like table rows.基本的东西可以工作,但我不知道如何在数组上使用像forEach()这样的循环来创建表行之类的东西。 I created a basic example:我创建了一个基本示例:

var domo = require('domo');

var fruits = [];
fruits.push("banana", "apple", "peach");

var document = DOCUMENT({type: "html"},
  HTML(
    HEAD(
      TITLE("bla"),
      SCRIPT({src: "/script.js"})
      ),
    BODY(
      TABLE(
        THEAD( TR( TD("Predicate"), TD("Object"))),
        TBODY(
          fruits.forEach(function(value, index) {
            console.log("I am in forEach");
            console.log("Value: "+value);
            console.log("Key: "+index);
            TR(
              TD(index),
              TD(value)
              )
          })
          )
        )

      )
    )).outerHTML;

console.log(document);

This currently results in this output:这当前导致此输出:

<!DOCTYPE html>
<html>
    <head>
        <title>
            bla
        </title>
        <script src="/script.js" type="text/javascript">
</script>
    </head>
    <body>
        <table>
            <thead>
                <tr>
                    <td>
                        Predicate
                    </td>
                    <td>
                        Object
                    </td>
                </tr>
            </thead>
            <tbody>
                <!--undefined-->
            </tbody>
        </table>
    </body>
</html>

If I get that correctly I cannot access the scope of domo within the forEach loop.如果我正确理解,我将无法访问 forEach 循环中的 domo 范围。 Is this the right interpretation and what would be the correct working way to do that?这是正确的解释吗?正确的工作方式是什么?

Solution :解决方案

Thanks to the hint from Bergi and a fix by Jed Schmidt this fragment now works (domo >=0.5.5):感谢来自 Bergi 的提示和 Jed Schmidt 的修复,这个片段现在可以工作(domo >=0.5.5):

TBODY( fruits.map(function(value, index) {
  return TR(
    TD(String(index)),
    TD(value)
    );
}))
)

forEach returns undefined after having iterated the array. forEach迭代数组后返回undefined

I don't know whether those functions accept arrays as arguments, but you might try map :我不知道这些函数是否接受数组作为参数,但您可以尝试map

TBODY( fruits.map(function(value, index) {
    console.log("I am in map");
    console.log("Value: "+value);
    console.log("Key: "+index);
    return TR(
//  ^^^^^^ dont forget this
        TD(index),
        TD(value)
    );
}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM