对于循环和阵列问题-ngRepeat
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++
,它会循环通过0-6,"灰色"answers"黑色"之间的所有内容都是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 ...
相关文章:
- 在指令控制器中使用$attrs时出现问题
- 将PHP变量传递给jQuery时遇到问题
- Canvas Html5绘图应用程序,移动画布会导致重大问题
- 参数变量出现ngTable指令问题
- 剑道网格jQuery动画()问题
- 我的jQuery插件参数没有正确启动,遇到了问题
- Phonegap-(安卓/iphone)多个图像的图像库出现问题
- TableExport jquery插件:文件名和扩展名问题
- JavaScript Pub/Sub属性访问问题
- JavaScript异步问题
- 如何解决Yii中的页面刷新问题
- 阵列中随机图像的问题
- 序列阵列问题
- 对于循环和阵列问题-ngRepeat
- 阵列在拼接后不会改变它的数据.范围问题
- 在改变阵列位置和以角度动态显示内容时遇到问题
- 阵列的异步问题
- 用于循环打印出整个阵列的问题
- JSON获取键/值:如果不存在,JS就停止.如何解决设置阵列的问题
- 是什么导致我的阵列出现此问题.