2017-02-19 103 views
0

我測試出的NodeJS模塊x-raycheerio無法遍歷數組

以下是我的代碼:這裏

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

const xray = new Xray(); 

xray('https://news.ycombinator.com/', '[email protected]')((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

我檢查了元素數組的類型,我得到Arrayarray作爲類型。那麼爲什麼循環只運行一次?

+0

使用與更新腳本中的差異elementsArray.each(功能(鍵,值){控制檯。日誌('message here')}); –

+0

你確定嗎?控制檯通常合併同一條消息的重複,只有一個出現計數器在它旁邊。 – trincot

+0

@KhanShahrukh爲什麼我會在迭代器中使用'key,value' - 我遍歷一個數組right,而不是對象/ map – callmekatootie

回答

1

消息顯示很多次,但控制檯會將同一消息的重複(同一個消息的重複內容)合併到一行中,旁邊有一個計數器。

如果您要更改消息使其每次都具有唯一性,您會看到不同之處。

舉例來說,如果你想使用索引消息:

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

查看runkit.com