简体   繁体   中英

JavaScript: Adding & Removing objects from array

var layers = {};

//Add new layer
layer.markers = new L.Group();
layer.Name = t;

layers.layer = layer;

Gives an error layers.length is still 'undefined'. Why is it doing that ? I have verified in log that layers contains an item.

layers is not an array. If you want to keep it as an object literal, and check if it's empty, try defining something like this:

Object.isEmpty = function(obj) {
    for (var p in obj)
        if (obj.hasOwnProperty(p)) return false;
    return true;
};

And use

if (!Object.isEmpty(layers)) { ...

instead.

You're not adding to the array. The last line should be:

layers.push(layer);

Simple question. layers is an object not an array .

What you needs to do is replace layers to following.

var layers = new Array();

And replace adding layer code from

layers.layer = layer;

to

layers.push(layer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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