推送到数组从变量中获取的键名
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;
相关文章:
- Javascript:无法获取变量中的单选按钮值
- 活动选项卡's源代码-获取变量s值
- 使用nodejs从url中获取变量
- Handlebars帮助程序未获取变量的值
- 通过Ajax获取变量
- for 循环和 if 语句,获取变量并存储它
- 从javascript表达式(Rhino)中获取变量
- 如何从 Chrome 扩展程序中的内容脚本中获取变量
- 从对象实例中获取变量名称
- 如何通过 .get() 从文件中获取变量
- 使用chrome.storage.get获取变量
- Rails/JS-在不刷新页面的情况下获取变量
- Jquery:如何获取变量的局部外部函数
- 从外部js文件获取变量
- 如何获取变量's设置元素时的文字值's onclick处理程序
- 从查询字符串中获取变量,将其与Javascript中的数组匹配
- 如何在另一个php文件中从ajax获取变量
- 通过Ajaxrequest.open从Javascript获取变量到PHP文件
- Jade:在Bootstrap Modal中获取变量
- 使用Chrome扩展从以前的选项卡中获取变量