gpt4 book ai didi

backbone.js - 获取集合长度

转载 作者:行者123 更新时间:2023-12-03 18:43:54 34 4
gpt4 key购买 nike

使用lobb.js并尝试从postsList数组中获取数据,我在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个模型。我不知道如何获得他们的数量。

最佳答案

是的,这是奇怪的行为:)

使用console.log后,Chrome会立即显示对象预览。
当您输入console.log(collection)时,它为空(可能是您已从服务器获取了模型)。但是,当您在控制台中展开对象时,Chrome会当前显示实际的对象参数。

在控制台中尝试以下操作:

var object = {key1:{prop:true}};
console.log(object)
object.key2 = true;
console.log(object)

要获取集合长度,请使用以下方式:
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

关于backbone.js - 获取集合长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14527755/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com