node.js - Cheerio map 奇怪的行为

标签 node.js cheerio

我正在使用带有Cheerio结果列表的map返回属性值。我想要的是一个包含属性值列表(在本例中为ID)的变量,但是我却在获取ID和额外的数据。

以下代码显示ID的列表:

let ids = $('[data-profileid]').map(function() {
    console.log($(this).attr('data-profileid'))
})

结果:
1012938412
493240324
123948532
423948234
...

但是,以下代码以不同的格式返回ID:
let ids = $('[data-profileid]').map(function() {
    return $(this).attr('data-profileid')
})

console.log(ids)

结果:
...
'69': '234234234,
'70': '9328402397432',
'71': '1324235234',
  options:
   { withDomLvl1: true,
     normalizeWhitespace: false,
     xmlMode: false,
     decodeEntities: true },
  _root:
   { '0':
      { type: 'root',
        name: 'root',
        attribs: {},
...

这些额外的数据是什么?当然不是必需的。我宁愿只有一个普通的数组。

最佳答案

根据http://api.jquery.com/map/:

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.



所以看起来这应该工作:
let ids = $('[data-profileid]').map(function() {
    return $(this).attr('data-profileid')
}).get()

关于node.js - Cheerio map 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39044690/

相关文章:

javascript - 无法从 github insights 页面抓取贡献者 div

javascript - 在 NodeJS 中使用嵌套回调时遇到问题

JavaScript:For循环自动构建多维数组

javascript - 抓取 JS 渲染页面的方法?

javascript - 从 React 组件内部使用 Electron ipcRenderer

node.js - Heroku nodejs-将 HTTP 重定向到 HTTPS

javascript - 如何从浏览器使用 cheerio

javascript - 使用 Cheerio 获取元素内部的元素

javascript - 在 Windows 上安装 GameClosure

javascript - ES6 : Emitting events from static methods