【问题标题】:How to echo elements of array in a callback for a forEach如何在 forEach 的回调中回显数组元素
【发布时间】:2015-08-15 00:17:57
【问题描述】:

我想echo 链接数组的内容。尝试使用这个:

casper.then(function() {
    // aggregate results for the 'casperjs' search
    links = this.evaluate(getLinks);
    links.forEach(function (element, index, array) {
        echo(element);
    });
});

但是得到一个错误:

TypeError: 'undefined' is not a function (evaluating 'this.echo(element)')

如何将每个链接回显到控制台?

【问题讨论】:

  • 我担心这是一个诡计问题。
  • 你在哪里定义了echo函数?错误消息和您的代码不匹配。
  • 请考虑我是 Javascript 的初学者。我正在从虚拟终端运行它。 console.log 不会在终端上回显任何内容。
  • 请编辑您的问题以更改代码或错误消息,因为它们不匹配。代码中没有this.echo(..),只有echo(...)

标签: javascript casperjs


【解决方案1】:

根据文档,它是“this.echo”;但是,由于“this”可能会根据上下文发生变化,因此您需要保存父上下文:

casper.then(function() {
    var self=this;
    // aggregate results for the 'casperjs' search
    links = this.evaluate(getLinks);
    links.forEach(function (element, index, array) {
        self.echo(element);
    });
});

http://docs.casperjs.org/en/1.1-beta2/modules/casper.html

【讨论】:

    【解决方案2】:

    替换

    echo(element);
    

    console.log(element);
    

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 2020-02-19
      • 1970-01-01
      • 2019-04-18
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多