繁体   English   中英

如何动态创建JavaScript对象?

[英]How do I create an javascript object dynamically?

我正在尝试创建用于在地图上放置点的位置对象。

我的代码是:

    var Locs = [{}];
    var title = '', content = '';

    for (i = 0; i < locations.length; i++) {


      content = '<div id="bodyContent">' +
                '<p><b>' + locations[i][0] + '</b><br />' +
                locations[i][4] +
                '</div>';

         Locs[i]['lat']   = locations[i][1];
         Locs[i]['lon']   = locations[i][2];
         Locs[i]['zoom']  = zoom;
         Locs[i]['title'] = locations[i][0];
         Locs[i]['html']  = content;

    }

我不断收到错误消息: TypeError: Locs[i] is undefined如果我将i替换为0,它将在地图上显示一个点。

我需要输出的是:

var Locs = [
    {
        lat: 45.9,
        lon: 10.9,
        zoom: 3,
        title: 'Title A1',
        html: '<h3>Content A1</h3>'
    },
    {
        lat: 44.8,
        lon: 1.7,
        zoom: 3,
        title: 'Title B1'
        html: '<h3>Content B1</h3>'
    },
    {
        lat: 51.5,
        lon: -1.1,
        zoom: 3,
        title: 'Title C1',
        html: '<h3>Content C1</h3>'
    }
];

因此,我想知道是否有人可以向我解释关于动态创建对象的不了解之处?

您必须先创建一个新object然后才能访问它,

Locs[i] = {};
Locs[i]['lat']   = locations[i][1];
Locs[i]['lon']   = locations[i][2];
Locs[i]['zoom']  = zoom;
Locs[i]['title'] = locations[i][0];
Locs[i]['html']  = content;

如果您不创建它,那么您的代码将被评估为:

Locs[i]['lat']
undefined['lat'] //will throw error here.

由于错误状态,您正在尝试为未定义的对象创建新的键。 在为对象分配值之前,需要先创建它。

当您执行var Locs = [{}]; ,它将创建一个带有一个空对象的数组,这就是为什么当您将i替换为0时它可以工作的原因。您可以添加Locs[i] = {}; 在分配纬度以创建一个空对象之前,或者直接在类似位置之前: Locs.push({lat: locations[i][1], long: locations[i][2], ...etc});

为每个循环初始化数组。 此代码将帮助您:

var Locs = [];
Locs[1] = [];
Locs[1]['lat'] = 123;
Locs[1]['long'] = 123;
Locs[2] = [];
Locs[2]['lat'] = 123;
Locs[2]['long'] = 123;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM