我想要这样的数组:-
arr[0][from] = value
arr[0][to] = value
arr[1][from] = value
arr[1][to] = value
。 。 等等。
我有 from 和 to 字段的输入数组 html 元素。
<input type="text" name="from[]" value=""/>
<input type="text" name="to[]" value=""/>
现在,我正在从下面的代码创建数组,它在控制台中给我错误,例如“Uncaught TypeError:无法读取未定义的属性'push'”。
var arr = [];
$('input[name^=from]').each(function(index,val) {
var from = $(this).val();
if(typeof arr[index] === undefined)
arr[index] = [];
arr[index].push({from:from});
});
$('input[name^=to]').each(function(index,val) {
var to= $(this).val();
if(typeof arr[index] === undefined)
arr[index] = [];
arr[index].push({to:to});
});
即使我写 arr[index]['from'] = from
而不是 arr[index].push({from:from});
那么也给出错误。
请大家帮我解决这个问题。提前致谢。
最佳答案
如果 index
处的对象未定义,则需要推送,否则更新它。您不需要使用 typeof
var arr = [];
$('input[name^=from]').each(function(index,val) {
var from = $(this).val();
if (arr[index] === undefined) {
arr[index] = {from: from};
} else {
arr[index].from = from;
}
});
$('input[name^=to]').each(function(index,val) {
var to= $(this).val();
if (arr[index] === undefined) {
arr[index] = {to: to};
} else {
arr[index].to = to;
}
});
var arr = [];
$('input[name^=from]').each(function(index, val) {
var from = $(this).val();
if (arr[index] === undefined) {
arr[index] = {
from: from
};
} else {
arr[index].from = from;
}
});
$('input[name^=to]').each(function(index, val) {
var to = $(this).val();
if (arr[index] === undefined) {
arr[index] = {
to: to
};
} else {
arr[index].to = to;
}
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="from[]" value="1" />
<input type="text" name="to[]" value="1" />
<input type="text" name="from[]" value="2" />
<input type="text" name="to[]" value="2" />
关于javascript - 如何用jquery制作动态关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41184325/