如何在Javascript中创建多维数组?

时间:2015-12-03 07:18:43

标签: javascript jquery

我需要创建一个这样的数组:

events: [
    id   :'1',
    title: 'All Day Event'
},{
    id   : '2',
    title: 'some name'
},{
    id: 999,
    title: 'some title',
}]

我在循环中执行此代码:

$events['title'] = 'hello';
$events['id'] = '1';

它回来了:

[ title: "hello", id: "1" ]
[ title: "hello", id: "1" ]

如何更改代码以满足我的要求?

2 个答案:

答案 0 :(得分:1)

尝试:

    var id1 = '1';
    var title1 = 'All Day Event';
    var events = [];
    events.push({
            id   :id1,
            title: title1
          });

循环:

titles = ['All Day Event1','All Day Event2'];
ids = ['1','2'];//note both array need to have the same length

$.each(titles,function(i,v){
 events.push({
                id   :ids[i],
                title: titles[i]//or v
              });
})

答案 1 :(得分:0)

查看一些示例here,并阅读有关JSON

的更多信息

您需要在添加维度和值的同时迭代JSON