如何编写循环遍历给定数组并按指定格式输出每条数据的姓名和年龄
实现代码
原示例数组存在2处可优化点:
- 最后一个对象的
hobbies属性中tennis未加字符串引号,运行时会抛出语法错误,已在下方代码中补全 - 部分姓名值末尾带多余空格,遍历处理时做了去空格处理,输出格式更规整
JavaScript 版本
// 修复后的示例数组 const example = [ {"name":"Ana","age": 16,"country":'india','hobbies':['futboll']} , {'name' :'Leo ' ,'age' : 20 , ' country ' : ' USA' ,'hobbies ' : ['fishing']}, {'name':'Mia ' , 'age' : 64 , 'country ' : 'cuba' , ' hobbies ' :['read']}, {'name':'Ian','age':43,'country':'france','hobbies':['tennis']} ] // 遍历输出 example.forEach(item => { const cleanName = item.name.trim() console.log(`${cleanName}(has ${item.age} years)`) })
Python 版本
# 修复后的示例数组 example = [ {"name": "Ana", "age": 16, "country": 'india', 'hobbies': ['futboll']}, {'name': 'Leo ', 'age': 20, ' country ': ' USA', 'hobbies ': ['fishing']}, {'name': 'Mia ', 'age': 64, 'country ': 'cuba', ' hobbies ': ['read']}, {'name': 'Ian', 'age': 43, 'country': 'france', 'hobbies': ['tennis']} ] # 遍历输出 for item in example: clean_name = item['name'].strip() print(f"{clean_name}(has {item['age']} years)")
输出结果
- Ana(has 16 years)
- Leo(has 20 years)
- Mia(has 64 years)
- Ian(has 43 years)
内容的提问来源于stack exchange,提问作者Juan Taylor
相关产品推荐
相关产品推荐

