我有一个数组,其中包含一些数据,名为 data
.
数据如下:
var data = [
{
id: 1,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'Gray',
choice_no: 1
},
{
id: 2,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'one',
choice_no: 2
},
{
id: 3,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'two',
choice_no: 2
},
{
id: 4,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'three',
choice_no: 2
},
{
id: 5,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'four',
choice_no: 2
},
{
id: 6,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'five',
choice_no: 2
},
{
id: 7,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'Black',
choice_no: 1
},
];
我目前正在尝试循环data
将它们分成两个单独的数组: color
和size
.
现在data
的对象并不总是有 choice1
或choice2
作为属性。 (只是稍后的旁注)
我正在检查第二个选择并执行循环:
if (data[0].choice2) {
// Has 2 choices
for (var i in data) {
if (data[i].choice1.toUpperCase() == 'SIZE' && data[i].choice_no == 1) {
size[i] = {
choice: data[i].choice,
order: data[i].sort
};
} else if (data[i].choice2.toUpperCase() == 'SIZE' && data[i].choice_no == 2) {
size[i] = {
choice: data[i].choice,
order: data[i].sort
};
} else if (data[i].choice1.toUpperCase() == 'COLOR' && data[i].choice_no == 1) {
color[i] = {
choice: data[i].choice,
order: data[i].sort
};
} else if (data[i].choice2.toUpperCase() == 'COLOR' && data[i].choice_no == 2) {
color[i] = {
choice: data[i].choice,
order: data[i].sort
};
}
} // End for()
}
这种类型有效。 color.length
= 7,但是,当它应该只等于 2 时。如果我像这样循环它:
for ( var x in color ) {
console.log(color[x]);
}
它输出:
Object {choice: "Gray", order: 2}
Object {choice: "Black", order: 1}
但是如果我将循环更改为 var x = 0; x < color.length; x++
它循环 0-6,“灰色”和“黑色”之间的所有内容都是 undefined
。现在我只使用第一个循环,因为它“有效”,但是 ngRepeat
工作原理与第二个数组类似。它循环遍历所有 7 条记录。
TL;DR
我很确定我的 if
上的某个地方搞砸了阻止试图分离choice1
和choice2
进入适当的数组(颜色和大小)。
值得注意的是choice1
重要 不总是颜色( choice1
可能是尺寸),甚至可能没有任何选择。而且我对修改数据的方式也非常有限。
最佳答案
不要使用索引设置数组,而是尝试使用方法 .push()
像这样:
if (data[i].choice1.toUpperCase() == 'SIZE' && data[i].choice_no == 1) {
size.push({ // <--- .push( instead of [i] =
choice: data[i].choice,
order: data[i].sort
});
} else ...
关于javascript - For 循环和数组问题 - ngRepeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28547773/