Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 收集不';在模板中不工作_Javascript_Backbone.js_Underscore.js - Fatal编程技术网

Javascript 收集不';在模板中不工作

Javascript 收集不';在模板中不工作,javascript,backbone.js,underscore.js,Javascript,Backbone.js,Underscore.js,我将模型发送到模板。模型有一个集合。在模板中,我回显了一些变量和函数: console.log(comments); console.log(_.size(comments)); console.log(comments instanceof App.Collections.Comments); console.log(_.pluck(comments, 'created')); _.each(comments, function(com) { console.log(com); });

我将模型发送到模板。模型有一个集合。在模板中,我回显了一些变量和函数:

console.log(comments);
console.log(_.size(comments));
console.log(comments instanceof App.Collections.Comments);
console.log(_.pluck(comments, 'created'));
_.each(comments, function(com) {
    console.log(com);
});
前三个有效,但后两个下划线函数无效。Pulk给出3个未定义的值,每个值不迭代

Object { length=3, models=[3], _byId={...}, more...}
3
true
[undefined, undefined, undefined]

如何使下划线函数工作?

您需要直接在集合上调用Pulk,因为集合类支持它:

因此,不是:

_.pluck(comments, 'created')
你可以打电话:

comments.pluck('created');
主干集合,以便您可以直接在集合实例上使用下划线方法:

console.log(comments.pluck('created'));
comments.each(function(com) { console.log(com) });
演示:

这个:

console.log(_.size(comments));
对您来说效果很好,因为
\uu0.size
如下所示:

_.size = function(obj) {
  return _.toArray(obj).length;
};
并调用集合的
toArray

// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
  if (!iterable)                return [];
  if (iterable.toArray)         return iterable.toArray();
  if (_.isArray(iterable))      return slice.call(iterable);
  if (_.isArguments(iterable))  return slice.call(iterable);
  return _.values(iterable);
};

它将展开集合的数据,以提供正确的长度。以上内容摘自1.3.1源代码,'s
.size
具有不同的实现,因此您的
.size
调用可能在升级过程中中断。

没问题,很高兴我们能提供帮助!