我们有一个这样的对象数组-
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