[英]javascript: push to multi dimensional array (name associated)
我想創建一個數組:
myarray:array [
"test1" = [
[0] =
{
name: "mike",
friend: "tom"
}
]
]
"test2": [
[0] =
{
name: "mike",
friend: "tom"
}
],
[1] =
{
name: "mike",
friend: "tom"
}
]
]
]
我如何動態添加對象?
在PHP我會做這樣的事情:
$content = {name: "robert", friend: "mike"}
$myarray[$group][] = $content; // Group is the dynamic element
在Javascript中我試試這個:
myarray[group].push({
name: "mike", friend: "-"
})
// group is the dynamic element
但他失敗了,在第一次通話時無法調用未定義的方法'push' 。
我不知道有多少“組”,所以我不能用所有組初始化數組。
使用object而不是數組來保存信息:
例:
function addUser(users, user, group) {
if (!users[group]) {
users[group] = [];
}
users[group].push(user);
return users;
}
var users = {};
users = addUser(users, {name: "mike", friend: "-"}, 'test1');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.