对于循环和阵列问题-ngRepeat

For Loop And Array Issue - ngRepeat

本文关键字:阵列 问题 -ngRepeat 循环 于循环      更新时间:2023-12-08

我有一个数组,它包含一些名为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,将它们分离为两个独立的数组:colorsize

现在data的对象将不总是以choice1choice2作为属性。(只是后面的旁注)

我正在检查第二个选择,并按如下方式循环:

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块上的某个地方搞砸了,试图将choice1choice2分离成合适的数组(颜色和大小)。需要注意的是,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 ...