简体   繁体   English

如何动态创建JavaScript对象?

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

I am trying to create an object of locations for placing points on a map. 我正在尝试创建用于在地图上放置点的位置对象。

My code is: 我的代码是:

    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;

    }

I keep getting an error: TypeError: Locs[i] is undefined If I replace i with 0 it works for displaying one point on the map. 我不断收到错误消息: TypeError: Locs[i] is undefined如果我将i替换为0,它将在地图上显示一个点。

What I need to output is: 我需要输出的是:

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>'
    }
];

So I am wondering if someone can explain to me what I don't understand about creating an object dynamically? 因此,我想知道是否有人可以向我解释关于动态创建对象的不了解之处?

You have to create a new object first before accessing that, 您必须先创建一个新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;

If you do not create it then your code would be evaluated like, 如果您不创建它,那么您的代码将被评估为:

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

As the error states, you are trying to create new keys to an object that is undefined. 由于错误状态,您正在尝试为未定义的对象创建新的键。 Before assigning values to an object, you need to create it. 在为对象分配值之前,需要先创建它。

When you do var Locs = [{}]; 当您执行var Locs = [{}]; , it creates an array with one empty object, that's why it works when you replace i by 0. You can either add Locs[i] = {}; ,它将创建一个带有一个空对象的数组,这就是为什么当您将i替换为0时它可以工作的原因。您可以添加Locs[i] = {}; before assigning the latitude to create an empty object, or directly something like: Locs.push({lat: locations[i][1], long: locations[i][2], ...etc}); 在分配纬度以创建一个空对象之前,或者直接在类似位置之前: Locs.push({lat: locations[i][1], long: locations[i][2], ...etc});

Initiate arrays for each loop. 为每个循环初始化数组。 This code will help you: 此代码将帮助您:

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