简体   繁体   English

如何使用JavaScript动态创建数组

[英]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. 我试图用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);' 我的日志文件以某种方式说无法调用'iconsetup.myicons [0] .push(icon);'上的undefined方法推送 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 您正在使用myicons[0] ,这意味着您将获得myicons的第一项,而不是数组

Use 采用

iconsetup.myicons.push(icon);

You could also simplify the whole .each() section with 您还可以通过以下方式简化整个.each()部分

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[0] 无所不能 iconsetup.myicons is simply an empty array with nothing in it, and no element 0. Maybe you meant: iconsetup.myicons只是一个空数组,其中没有任何内容,并且没有元素0。也许您是说:

iconsetup.myicons.push(icon);

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

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