最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Push to array a key name taken from variable - Stack Overflow

programmeradmin6浏览0评论

I have an array:

var pages = new Array();

I want to push my pages data to this array like this:

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

but this code doesn't replace datatype as variable, just puts datatype string as a key. How do I make it place there actual string value as a key name?

I have an array:

var pages = new Array();

I want to push my pages data to this array like this:

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

but this code doesn't replace datatype as variable, just puts datatype string as a key. How do I make it place there actual string value as a key name?

Share Improve this question asked Mar 16, 2012 at 20:32 Sergei BasharovSergei Basharov 53.9k78 gold badges207 silver badges352 bronze badges 1
  • Possible duplicate of JavaScript Array of Key/Value Pairs Uses Literal Variable Name for Key – Azteca Commented Nov 28, 2017 at 22:13
Add a ment  | 

5 Answers 5

Reset to default 10

I finally saw what you were trying to do:

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);
});

Notice that you can put a ma between variable declarations rather than reusing the var keyword.

It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:

pages_order.push([datatype, info]);

You have to use datatype in a context where it will be evaluated.

Like so.

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);
});

You only need one var it can be followed by multiple assignments that are separated by ,.

No need to use new Array just use the array literal []

You may add below single line to push value with key:

pages_order.yourkey = value;
发布评论

评论列表(0)

  1. 暂无评论