JavaScript中如何按指定格式打印对象数组
如何按指定格式打印JavaScript学生对象数组
没问题,这有几种简单易懂的方法来实现你想要的打印格式,我会给你逐一拆解:
首先,先确认我们的原始数据结构(你给出的学生对象和数组):
const vStu1 = {id:"12345", name:"Dave Smith", testScore:10}; const vStu2 = {id:"43531", name:"Emma Black", testScore:17}; const vStu3 = {id:"97894", name:"Sue Davies", testScore:14}; const arrStudents = [vStu1, vStu2, vStu3];
方法1:使用forEach循环(最直观)
这是遍历数组最常用的方式,逐个处理每个学生对象,按指定格式拼接字符串并打印:
arrStudents.forEach(student => { console.log(`ID: ${student.id} Name: ${student.name} TestScore: ${student.testScore}`); });
执行后控制台输出效果:
ID: 12345 Name: Dave Smith TestScore: 10
ID: 43531 Name: Emma Black TestScore: 17
ID: 97894 Name: Sue Davies TestScore: 14
方法2:使用map+join(一次性输出所有内容)
如果你想先把所有格式化后的字符串拼接成一个整体,再一次性打印,可以用这种方式:
// 先把每个学生转换成指定格式的字符串,再用换行符连接 const formattedText = arrStudents.map(student => `ID: ${student.id} Name: ${student.name} TestScore: ${student.testScore}` ).join('\n'); // 一次性打印所有内容 console.log(formattedText);
方法3:传统for...of循环
如果你习惯ES6之前的遍历语法,for...of也是个不错的选择:
for (const student of arrStudents) { console.log(`ID: ${student.id} Name: ${student.name} TestScore: ${student.testScore}`); }
可选优化:让格式更整齐
如果想让Name部分像你示例里的XXXXXXXXXX一样对齐,可以用字符串填充方法padEnd,自动补空格:
arrStudents.forEach(student => { // 把名字填充到12个字符长度,不够的补空格 const alignedName = student.name.padEnd(12, ' '); console.log(`ID: ${student.id} Name: ${alignedName} TestScore: ${student.testScore}`); });
优化后的输出会更规整:
ID: 12345 Name: Dave Smith TestScore: 10
ID: 43531 Name: Emma Black TestScore: 17
ID: 97894 Name: Sue Davies TestScore: 14
内容的提问来源于stack exchange,提问作者Aleksandar Jovanovski
相关产品推荐
相关产品推荐

