也许这不是问这个问题的合适地方,但我需要一个建议,因为我坚持这个。我有这段代码:
$(document).ready(function(){
var i = 0, j = 0,
manufacturerIds = [1,2,3,4,5,6,7],
countryIds = [1,2,3,4,5,6,7,8,9,10],
result = [];
for (i; i < manufacturerIds.length; i++) {
for (j; j < countryIds.length; j++) {
result.push({
i: {
idMan: manufacturerIds[i],
idCtr: [] // stuck on this point, don't know
// where to go from here and don't know
// if I'm doing things right
}
});
}
}
});
我正在尝试返回这样的输出:
[
{
"0": {
"idMan": 1,
"idCtr": [
1,
2,
3,
4,
5
]
},
"1": {
"idMan": 2,
"idCtr": [
1,
2,
3,
4,
5
]
},
"2": {
"idMan": 3,
"idCtr": [
1,
2,
3,
4,
5
]
}
}
]
可以给我一些建议吗?还是帮忙?
注意:我不确定这是正确的还是最好的方法,但我正在尝试构建某种结构,以便我可以区分对象|数组上的每个项目,为什么?因为我需要向其中添加新元素。例如,此输出也将有效:
[
{
"0": {
"idMan": 1,
"idCtr": [
1,
2
]
},
"1": {
"idMan": 1,
"idCtr": [
1,
4,
5
]
},
"2": {
"idMan": 1,
"idCtr": [
3
]
}
}
]
有了这个我想添加新的 idCtr
会很容易吧?通过访问 someVar[X].idCtr.push(newVal);
。顺便说一句,我写了一些 var 示例,但事实是这些值是动态的,只是让您了解我的疑问背后的想法的起点
最佳答案
我相信这更符合您的要求
var i = 0,
j = 0,
manufacturerIds = [1, 2, 3, 4, 5, 6, 7],
countryIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
result = [];
for (i; i < manufacturerIds.length; i++) {
/* create basic object*/
var item = {};
item[i] = {idMan: manufacturerIds[i],idCtr: []};
/* now push country Ids*/
for (var j=0;; j < countryIds.length; j++) {
item[i].idCtr.push(countryIds[j]);
}
/* finished creating object*/
result.push(item);
}
关于javascript - 从 Javascript 中的数组值生成有效输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27624544/