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
Push to array a key name taken from variable
提问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 datatype
as 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 var
keyword.
请注意,您可以在变量声明之间放置一个逗号,而不是重复使用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 datatype
in 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 var
it can be followed by multiple assignments that are separated by ,
.
您只需要一个var
它就可以跟多个以,
.
No need to use new Array
just use the array literal []
无需使用,new Array
只需使用数组文字[]
回答by Rafaqat
You may add below single line to push value with key:
您可以添加以下单行以使用键推送值:
pages_order.yourkey = value;