简体   繁体   中英

How to create array dynamically with javascript

Im trying something which is probably very easy but i cant seem to find out why its not working. Im trying to dynamically create and array with jquery/javascript.

my code;

var icons = $('.icon');

var desktopicons = [];

var user = { name: username };

var iconsetup = { myicons: [] };

desktopicons.push(user);
desktopicons.push(iconsetup);

$.each(icons, function() {
        var name = $(this).attr('name');
    var rel = $(this).attr('rel');


    var icon = { 
        icon: [{
            name: name,
            rel: rel
        }]
    };

    iconsetup.myicons[0].push(icon);

});

desktopicons.push(user);
desktopicons.push(iconsetup);

$('#desktop').append(desktopicons[0].name);
$('#desktop').append(desktopicons[1].myicons[0].icon[0].name);

Somehow my log file says cannot call method push of undefined on 'iconsetup.myicons[0].push(icon);' this line.

Anyone who can tell me how to create the array? Thanks!

You are using myicons[0] which means you get the first item of the myicons and that is not an array

Use

iconsetup.myicons.push(icon);

You could also simplify the whole .each() section with

iconsetup.myicons = icons.map(function(idx, item){
   return {icon:[{name: item.name, rel: item.rel}]}
}).get();

您正在尝试将图标推myicons[0]未定义的myicons[0] ,而是需要推送到myicons,这会将图标添加到数组中:

iconsetup.myicons.push(icon);

You never set iconsetup.myicons[0] equal to anything. iconsetup.myicons is simply an empty array with nothing in it, and no element 0. Maybe you meant:

iconsetup.myicons.push(icon);

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