向后循环对象数组

时间:2019-11-04 21:49:32

标签: javascript jquery loops

我知道这将是非常基本的,对此可能会被否决,但此刻我有点迷茫。

我有一个对象数组

let data = [
  {id:1, Name: "Abe", RowNumber: 1 },
  {id:2, Name: "Bob", RowNumber: 2 },
  {id:3, Name: "Clair", RowNumber: 3 },
  {id:4, Name: "Don", RowNumber: 3.0 },
  {id:5, Name: "Edna", RowNumber: 3.1 },
  {id:6, Name: "Frank", RowNumber: 3.2 },
  {id:7, Name: "Gabe", RowNumber: 4 },
  {id:8, Name: "Helen", RowNumber: 5 },
  {id:9, Name: "Isabelle", RowNumber: 6 },
  {id:10, Name: "Jane", RowNumber: 7 },
  {id:11, Name: "Ken", RowNumber: 8 },
];

我正在尝试使它们向后而不是向前循环,我想出了这个

for(let i = data.length; i != 0; i--){
    console.log(data[i].Name);
}

那是行不通的,我收到一个有关名称未定义的错误。

有人可以告诉我我要去哪里哪里

3 个答案:

答案 0 :(得分:2)

您从.length迭代到1(含)。进行一个减小的位置以从.length - 1迭代到0

答案 1 :(得分:1)

尝试一下:

let data = [
    { id: 1, Name: "Abe", RowNumber: 1 },
    { id: 2, Name: "Bob", RowNumber: 2 },
    { id: 3, Name: "Clair", RowNumber: 3 },
    { id: 4, Name: "Don", RowNumber: 3.0 },
    { id: 5, Name: "Edna", RowNumber: 3.1 },
    { id: 6, Name: "Frank", RowNumber: 3.2 },
    { id: 7, Name: "Gabe", RowNumber: 4 },
    { id: 8, Name: "Helen", RowNumber: 5 },
    { id: 9, Name: "Isabelle", RowNumber: 6 },
    { id: 10, Name: "Jane", RowNumber: 7 },
    { id: 11, Name: "Ken", RowNumber: 8 },
];
for (let i = data.length - 1; i >= 0; i--) {
    console.log(data[i].Name);
}

答案 2 :(得分:1)

您需要从长度减一到零进行循环。

这种方法在一个表达式中进行校验和减量。

let data = [
        { id: 1, Name: "Abe", RowNumber: 1 },
        { id: 2, Name: "Bob", RowNumber: 2 },
        { id: 3, Name: "Clair", RowNumber: 3 },
        { id: 4, Name: "Don", RowNumber: 3.0 },
        { id: 5, Name: "Edna", RowNumber: 3.1 },
        { id: 6, Name: "Frank", RowNumber: 3.2 },
        { id: 7, Name: "Gabe", RowNumber: 4 },
        { id: 8, Name: "Helen", RowNumber: 5 },
        { id: 9, Name: "Isabelle", RowNumber: 6 },
        { id: 10, Name: "Jane", RowNumber: 7 },
        { id: 11, Name: "Ken", RowNumber: 8 }],
    i = data.length;

while (i--) {
    console.log(data[i].Name);
}