我有一个名为 companies 的主干模型变量,它具有对象数组类型。通过把它放到控制台我得到这个:
这个对象加载了fetch函数:
require(["collections/Companies"],
function(Companies) {
var companies = new Companies();
companies.fetch();
console.log(companies[0].get("name"));
});
公司.js:
define([
'models/Company'
], function(CompanyModel) {
'use strict';
var CompanyCollection = Backbone.Collection.extend({
model: CompanyModel,
url: 'scripts/data/companies.json'
});
return CompanyCollection;
});
公司.js:
define([], function () {
'use strict';
var CompanyModel = Backbone.Model.extend({
defaults: {
id: '',
name: '',
description: ''
}
});
return CompanyModel;
});
我尝试根据 tutorials 使用 get 来获取属性(console.log(companies[0].get("name"));
) 运气不好。
获取属性的正确语法是什么?
提前致谢
最佳答案
要从集合中获取模型,您可以使用 Backbone 集合方法 - collection.at(INDEX);
示例代码:
var collection = new Backbone.Collection();
collection.add({ id: 1, name: "S"});
collection.add({ id: 2, name: "F"});
console.log(collection.at(0).attributes); // { id: 1, name: "S"}
var model = collection.at(0);
// get attributes from model
console.log(model.get("name")); // "S"
你可以玩demo
要从集合中获取模型,请使用:collection.models(您将获得模型数组)
关于javascript - 如何从对象数组中获取属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21810176/