如何在backbone.js中从模型中获取数组元素

how to get array element from model in backbone.js

本文关键字:模型 获取 数组元素 js backbone      更新时间:2023-10-01

我有以下代码:

Person = new Backbone.Model({
 data:[
    { age: "27" },
    {name: "alamin"}
]
});

现在,我怎样才能得到价值?

person=new Person();
person.get(?);

请给我一个解决方案。

如果您使用此模型:

Person = new Backbone.Model({
data:[
    { age: "27" },
    {name: "alamin"}
]
});

因此,如果你想明确地从模型中的数组中提取,你应该试试这个:

i = new App.Model.Person();
i.fetch();
i.get("data")[0].age;

这将返回:

27

从那里,您可以按照自己的喜好对数据进行迭代。

在定义模型时,我不知道数据属性——也许你指的是默认值?如

var Person = Backbone.Model.extend({
   defaults: {
      property1: value1,
      property2: value2,
      property3: ["arrval1", "arrval2", "arrval3"]
   });

您可以使用get:myphen.get('property1')检索某些属性的值。要设置属性的值,请使用set:myperson.set('property1','newValueOfProperty')

如果属性是一个数组,则myperson.get('property3')[index]

将数组作为对象:

使用person.get('data')

从数组中获取属性值:

使用person.get('data').name

person.get('data')['name']

获取数组中特定元素的属性:

var people = person.get('data'); // This gets the array of people.
var individual = people[0];      // This gets the 0th element of the array.
var age = individual.age;        // This gets the age property.
var name = individual.name;      // This gets the name property.