无法遍历数组

Unable to iterate over an array

我正在测试 nodejs 模块 x-ray and cheerio

以下是我的代码:

const Xray = require("x-ray");
const cheerio = require('cheerio');

const xray = new Xray();

xray('https://news.ycombinator.com/', 'body@html')((err, result) => {
    const $ = cheerio.load(`<body>${result}</body>`);

    const elements = $('body')
        .find('*')
        .filter((i, e) => (
            e.type === 'tag'
        ))
        .map((i, e) => {
            e.foo = {
                id: i
            };
            return e;
        })
        .filter((i, e) => (
            e.foo.id % 2 === 0
        ));

    const elementsArray = elements.toArray();

    console.log('Length of the array is:', elementsArray.length);

    elementsArray.forEach((e) => {
        console.log('I appear to print only once, even though elementsArray has lots of elements');
    });
});

这里的问题是 forEach 循环中的 console.log() 只打印一次——即使之前 console.log(elementsArray.length) 的输出大约是 369。

Runkit link to test it out

我检查了 elementsArray 的类型,我得到 Arrayarray 作为类型。为什么循环 运行 只执行一次?

该消息显示多次,但控制台会将同一消息的重复(一个词的内容)合并到一行中,并在其旁边显示一个计数器。

如果您更改消息以使其每次都独一无二,您就会看到不同之处。

例如,如果您要在邮件中使用索引:

elementsArray.forEach((e,i) => {
    console.log(i); // different message on every iteration
});

runkit.com

上查看与更新脚本的区别