繁体   English   中英

推送到数组从变量中取出的键名

[英]Push to array a key name taken from variable

我有一个数组:

var pages = new Array();

我想将我的页面数据推送到这个数组,如下所示:

$('li.page').each(function () {
        var datatype = $(this).attr('data-type');
        var info = $(this).attr('data-info');
        pages_order.push({datatype:info});
    });

但是这段代码不会将datatype替换为变量,只需将数据类型字符串作为键。 如何将实际字符串值作为键名放置?

我终于看到了你想要做的事情:

var pages = new Array();
$('li.page').each(function () {
    var datatype = $(this).attr('data-type');
    var info = $(this).attr('data-info');
    var temp = {};
    temp[datatype] = info;
    pages_order.push(temp);
});
$('li.page').each(function () {

    //get type and info, then setup an object to push onto the array
    var datatype = $(this).attr('data-type'),
        info = $(this).attr('data-info'),
        obj  = {};

    //now set the index and the value for the object
    obj[datatype] = info;
    pages_order.push(obj);
});

请注意,您可以在变量声明之间添加逗号,而不是重用var关键字。

看起来您只想为每个页面存储两条信息。 你可以通过推送数组而不是对象来做到这一点:

pages_order.push([datatype, info]);

您必须在将要评估它的上下文中使用datatype

像这样。

var pages = [];
$('li.page').each(function () {
    var datatype = $(this).attr('data-type'),
        info = $(this).attr('data-info'),
        record = {};
    record[datatype] = info;
    pages_order.push(record);
});

你只需要一个var可以接着由分隔的多个任务,

无需使用new Array只需使用数组文字[]

您可以添加以下单行以使用键来推送值:

pages_order.yourkey = value;

暂无
暂无

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

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