循环遍历 JavaScript 对象数组


我们有一个这样的对象数组 −

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 },
];

我们需要编写一个 JavaScript 函数,该函数接受此数组并返回一个字符串,其中名称从最后一个对象开始,一直到第一个对象,中间用 “,” 分隔

让我们编写此函数的代码 −

示例

const 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 },
];
const buildString = arr => {
   let str = '';
   for(let i = arr.length-1; i > -1; i--){
      str += `${arr[i]["Name"]}, `;
   };
   return str.substring(0, str.length-2);
};
console.log(buildString(data));

输出

控制台中的输出将是 −

Ken, Jane, Isabelle, Helen, Gabe, Frank, Edna, Don, Clair, Bob, Abe

更新日期: 31-08-2020

116 次浏览

开启您的 职业生涯

通过完成课程获得认证

入门
广告