获取集合长度 [英] Get collection length
问题描述
使用Backbone.js的,并试图从 postsList
阵列我在Chrome的console.log得到这个数据
Using backbone.js and trying to get data from postsList
array I got this in chrome console.log
d {length: 0, models: Array[0], _byId: Object, _byCid: Object, constructor: function…}
_byCid: Object
_byId: Object
length: 9
models: Array[9]
__proto__: f
当我试图使用的console.log(postsList.length)
我得到0,但也有9款车型中。我不知道如何让他们的数量。
When I'm trying to use console.log(postsList.length)
I get 0, but there are 9 models inside. I don't know how to get number of them.
推荐答案
是的,这是奇怪的行为:)
Yes, this is strange behaviour :)
Chrome会立即显示对象preVIEW您已经使用后,的console.log
。
当你输入的console.log(集合)
里面是空的(可能是您拥有从服务器获取模型)。而此刻,当您展开控制台中的Chrome对象在当前时刻显示实际的对象PARAMS。
Chrome displays object preview immediately after you have used console.log
.
When you entered console.log(collection)
it was empty (probably you have fetched model from the server). But at the moment when you expand the object in console Chrome displays actual object params at current moment.
试试这个:
var object = {key1:{prop:true}};
console.log(object)
object.key2 = true;
console.log(object)
要获得集合长度用这样的方式:
To get collection length use this way:
collection.fetch({context:collection}).done(function() {
console.log(this.length)
});
修改
没有 - 不 - 不:)
使用 this.length
而不是 this.lenght
。
collection.fetch({context:collection}).done(function() {
// equals to this.length
console.log(this.size());
// get all models from collection (array of Backbone.Models)
console.log(this.models);
// get all models from collection (like simple array of objects)
console.log(this.toJSON());
// get model with index 1
console.log(this.at(1));
// get model data with index 1
console.log(this.at(1).toJSON());
// get model with id `some-id`
console.log(this.get('some-id'));
// get models data where property `id_str` equals to `292724698935070722`
console.log(this.where({id_str:'292724698935070722'}));
});
有关更多信息,请看:
http://backbonejs.org/#Collection
For more information look here: http://backbonejs.org/#Collection
这篇关于获取集合长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!