Cheerio 地图奇怪的行为

Cheerio Map Strange Behaviour

我将 map 与 Cheerio 结果列表一起使用 return 属性值。我想要的是一个包含属性值列表(在本例中为 ID)的变量,但我得到的是 ID 和额外数据。

以下代码打印 ID 列表:

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

结果:

1012938412
493240324
123948532
423948234
...

但是,下面的代码 return 是不同格式的 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()

What is all this extra data? It certainly isn't required. I'd rather just have an ordinary array.

Cheerio 有一个 fluent API,这意味着它的大部分功能 return 一个可以链接其他功能的对象。如果 map 只是 return 编辑了一个 "ordinary array",那么您将无法对结果调用其他 Cheerio 函数。没有很多方法可以将额外的函数调用链接到 你的 map 调用的结果,return 是一个字符串数组,但是 Cheerio 的开发人员(从 jQuery 的开发人员那里得到启发)选择保持一致 API 而不是用特殊情况来填充它。

不过,如果您想要一个普通的数组,Cheerio 会为您提供一个方便的 toArray 函数:

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

console.log(ids.toArray());
// => [ '1012938412', '493240324', '123948532', '423948234' ]