2016-08-19 83 views
3

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

下面的代码打印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: {}, 
... 

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

回答

5

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

作为返回值是一个jQuery对象,其中包含一个阵列,它是 很常见的调用获得()的结果与一个基本阵列工作。

所以看起来这应该工作:

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

的感谢!这真的很有帮助。 – veldtmana

1

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

Cheerio具有流利 API,这意味着它的大部分函数返回在其上附加功能可以链接的对象。如果map刚刚返回了“普通数组”,那么您将无法对结果调用其他Cheerio函数。有没有很多的方法可以链附加功能调用到map调用,它返回一个字符串数组的结果,但Cheerio的开发人员(以从jQuery的开发人员的提示),选择保持一致的API,而不是用特殊情况胡椒粉。

如果你想要一个普通的数组,不过,Cheerio为您提供了一个方便的toArray功能:

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

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