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

Push to array a key name taken from variable

本文关键字:获取 变量 数组      更新时间:2023-09-26

我有一个数组:

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;