You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写循环遍历给定数组并按指定格式输出每条数据的姓名和年龄

实现代码

原示例数组存在2处可优化点:

  1. 最后一个对象的hobbies属性中tennis未加字符串引号,运行时会抛出语法错误,已在下方代码中补全
  2. 部分姓名值末尾带多余空格,遍历处理时做了去空格处理,输出格式更规整

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:15:03