如何使用jQuery获取对象的值数组

3
我有问题使用jQuery获取对象数组中的所有元素...
我从互联网上获取了这段代码...
var id = 123;
var test = new Object();
test.Identification = id;
test.Group = "users";
test.Persons = new Array();

test.Persons.push({"FirstName":" AA ","LastName":"LA"});
test.Persons.push({"FirstName":" BB ","LastName":"LBB"});
test.Persons.push({"FirstName":" CC","LastName":"LC"});
test.Persons.push({"FirstName":" DD","LastName":"LD"});

如何使用 JQuery 获取 Persons 中的“FirstName”和“LastName”?
4个回答

8
你可以使用$.each()$.map(),具体取决于你想要做什么。
$.map(Persons, function(person) {
    return person.LastName + ", " + person.FirstName;
});
// -> ["Doe, John", "Appleseed, Marc", …]

4
您可以使用$.each()来遍历数组。
$.each(test.Persons, function(index){
    alert(this.FirstName);
    alert(this.LastName);
});

您可以查看演示来了解更多信息。


1

你可以使用JavaScript语法来操作数组:

for(var i in test.Persons) {
    alert(test.Persons[i].FirstName + " " + test.Persons[i].LastName);
}

0

我认为使用jQuery有点过头了。

Array.forEach:

test.Persons.forEach(function(person) {
  alert(person.FirstName + " " + person.LastName);
});

或者仅通过索引:

alert(test.Persons[0].FirstName + " " + test.Persons[0].LastName);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接