我有一个person
的对象数组:
var p1 = {firstName:"John", lastName:"Doe", age:46};
var p2 = {firstName:"Joanne", lastName:"Doe", age:43};
如何将此数组添加到persons
数组并通过索引访问它?
我所知道的就是初始化persons
:
var persons = [
{firstName:"John", lastName:"Doe", age:46},
{firstName:"Joanne", lastName:"Doe", age:43}
];
答案 0 :(得分:4)
创建一组人:
var persons = []; // initialize the array
persons.push({firstName:"John", lastName:"Doe", age:46}); // Add an object
persons.push({firstName:"Joanne", lastName:"Doe", age:43}); // Add another object
要检索特定索引处的值:
persons[1].firstName // "Joanne"
persons[1].lastName // "Doe"
persons[1].age // 43
要遍历数组,请使用for
循环或任何类型的循环:
for (var i = 0; i < persons.length; i++) {
console.log( persons[i].firstName ); // writes first names to console
}
答案 1 :(得分:1)
创建array literal use []
而不是QByteArray ba = Serialize<int>(5);
...
int theValue = Deserialize<int>(ba);
。
答案 2 :(得分:1)
您可以使用push
方法添加每个对象
遍历您的数组并为每个persons.push(object)
循环。
答案 3 :(得分:0)
另一种遍历这些人的方法是:
const people = persons.map((person, i) => {
console.log(persons[i].firstName)
});
答案 4 :(得分:-1)
您可以使用推送方法 它会将对象添加到数组的末尾。
参见示例:
<script>
var per1 ={firstName:"John", lastName:"Doe", age:46};
var per2 ={firstName:"Johny", lastName:"Doe", age:50};
var persons = [per1,per2];
var per3 ={firstName:"Johnonon", lastName:"Doe", age:52};
persons.push(per3);
</script>
&#13;