[英]For Loop And Array Issue - ngRepeat
我有一个数组,其中包含一些称为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++
var x = 0; x < color.length; x++
var x = 0; x < color.length; x++
会通过0-6循环,并且“灰色”和“黑色”之间的所有内容都是undefined
。 现在,我将使用第一个循环,因为它“有效”,但是ngRepeat
工作原理类似于第二个数组。 它遍历所有7条记录。
我很确定自己在if
块中的某个地方弄乱了,试图将choice1
和choice2
分离为它们适当的数组(color和size)。 重要的是要注意, choice1
并非总是颜色( choice1
可以是size),甚至可能没有任何选择。 另外,我非常受限于如何修改数据。
而不是使用索引设置数组,请尝试使用方法.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 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.