骨干收集,countBy错误

Gio*_*ner 4 javascript arrays collections methods underscore.js

我有一个集合,我想通过计算其属性中的相同值来分组.所以我执行这个:

_.countBy(T.collection,function(model){
    return model.get('text')
})
Run Code Online (Sandbox Code Playgroud)

其中attribute是一个字符串.该字符串可以包含字母(Az),':'和'_'(下划线).它没有空白.

但代码抛出

无法调用未定义的方法'get'.

我也尝试过

T.collection.countBy(function(model){
    return model.get('text')
})
Run Code Online (Sandbox Code Playgroud)

但它会抛出

Object [object Object]没有方法'countBy'

mu *_*ort 7

countBy不是混合到集合中的Underscore方法之一,正如您所见,这不起作用:

T.collection.countBy(function(model){ return model.get('text') });
Run Code Online (Sandbox Code Playgroud)

并且集合不是数组,因此这也不起作用:

_.countBy(T.collection,function(model){ return model.get('text') });
Run Code Online (Sandbox Code Playgroud)

当你这样做时model,它不会是集合中的模型,它将是T.collection对象属性的值之一; 例如,这个:

_({where: 'is', pancakes: 'house?'}).countBy(function(x) { console.log(x); return 0 });???
Run Code Online (Sandbox Code Playgroud)

会给你ishouse?控制台.

但是,T.collection.models是一个数组,一个模型数组.这意味着这应该工作:

_.countBy(T.collection.models, function(model) { return model.get('text') });
Run Code Online (Sandbox Code Playgroud)

我建议在你的收藏中添加它作为一种方法,这样外人就不必乱搞集合的models属性了.