我正在使用多维数组来存储数据。它工作,但当我们在控制台中打印它显示空白数组,并在其下显示两个数组,它应该只显示一个数组内。 它看起来应该是这样的。
ar['outbound']['Meal']="111,121"
它在控制台中看起来像这样
还打印undefined还有一件事
如何从上一个
中删除“,”这是fiddle
代码
var ar = [];
ar['Outbound'] = [];
ar['Inbound'] = [];
var ch="";
var sr= [];
sr['Meal']= [];
sr['Lounge']= [];
$('a').click(function(){
ch = $(this).parent().find('.no').text();
var boundType= $(this).parent().find('.bound').text();
ar[boundType][$(this).parent().find('.service').text()] +=($(this).parent().find('.no').text()) + ","; console.log(ar)
})
答案 0 :(得分:1)
问题在于:
ar[boundType][$(this).parent().find('.service').text()] +=($(this).parent().find('.no').text()) + ",";
将其替换为:
var temp = $(this).parent().find('.service').text();
ar[boundType][temp] = (ar[boundType][temp] + "," || '') + ($(this).parent().find('.no').text());
检查变量是否存在。
此外,数组不能将字符串作为索引。而是使用对象:
var ar = {};
ar['Outbound'] = {};
ar['Inbound'] = {};
// etc...
答案 1 :(得分:1)
要避免“未定义”,您必须为数组项设置默认值:
if (!ar[boundType][service]) {
ar[boundType][service] = '';
}
最好在添加新值之前添加',':
if (ar[boundType][service].length > 0) {
ar[boundType][service] += ',';
}