javascript 将取自变量的键名推送到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9744127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:40:58  来源:igfitidea点击:

Push to array a key name taken from variable

javascriptjqueryhtml

提问by Sergei Basharov

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 datatypeas variable, just puts datatype string as a key. How do I make it place there actual string value as a key name?

但此代码不会替换datatype为变量,只是将数据类型字符串作为键。我如何让它把实际的字符串值作为键名?

回答by nathanjosiah

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

回答by Jasper

$('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 comma between variable declarations rather than reusing the varkeyword.

请注意,您可以在变量声明之间放置一个逗号,而不是重复使用var关键字。

回答by Justin Ethier

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

回答by zellio

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

您必须datatype在将对其进行评估的上下文中使用。

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 varit can be followed by multiple assignments that are separated by ,.

您只需要一个var它就可以跟多个以,.

No need to use new Arrayjust use the array literal []

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

回答by Rafaqat

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

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

pages_order.yourkey = value;