您好我想在javascript中创建一个数组
var sortValues = array(
2 => array(3,4,5),
3 => array(5,6,7),
12 => array (7,4,5)
);
现在我循环遍历表单的所有文本框。每个文本框的id都是2_3
,表示2将是数组的主索引。
我的html标记看起来像
<input type="text" value="3" id="2_5" name="2_5">
<input type="text" value="4" id="2_5" name="2_6">
<input type="text" value="5" id="2_5" name="2_7">
<input type="text" value="5" id="3_1" name="3_1">
<input type="text" value="6" id="3_2" name="3_2">
..................................
现在我想检查数组sortValues
中是否存在2,我将获取文本框的值,并将检查数组中是否存在此值,然后我将发出一个已经值的警报存在,如果值不存在则按子数组中的值。意味着我需要将3对2放入,我将检查3是否存在2,如果是,则将其他信息推入数组。
如果2(主索引)不存在,则在数组中创建新索引,依此类推。到目前为止我已经尝试了
var sortvalues = new Array();
$(":text").each(function () {
if($(this).val() != '') {
id = $(this).attr('id');
ids = id.split("_");
parent = ids[0];
child = ids[1];
if(typeof sortvalues[parent] !== 'undefined') {
if(typeof sortvalues[parent][$(this).val()] !== 'undefined') {
alert("Value already exists");
} else {
sortvalues[parent][] = $(this).val();
}
} else {
sortvalues.push(parent);
}
}
});
console.log(sortValues);
哪会给["2", "2", "2"]
哪个错误。可以任何机构指导我如何在上述标准中实现上述数组?? /
答案 0 :(得分:0)
你的意思是在另一个数组中创建一个数组吗?
例如:
var sortValues = new Array();
sortValues[2] = Array(3,4,5);
请澄清你的问题。以下内容:
sortvalues[parent][] = $(this).val() --> you can't leave empty for the second array.