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

为何传入用户数组时代码失效?如何输出全部用户信息?

问题分析与解决方案

失效原因

你写的UserFunc函数是为单个用户对象设计的,但你直接把整个用户数组传进去了:

  • 数组本身没有name和age属性,所以函数里的Users.name会返回undefined
  • 数组也不存在age属性,所以会进入else分支,输出无效的Name: undefined

只有当你传入数组里的单个用户对象(比如Users[0])时,函数才能正确读取对象的name和可选的age属性,所以这时候能正常运行。

输出全部用户的解决方法

要输出所有用户信息,你需要遍历整个用户数组,把每个用户对象单独传入UserFunc。常用的遍历方式有forEach循环:

// Give Users needed types
type typeUsers = { name: string; age?: number };
// List of users
const Users: typeUsers[] = [
    {
        name: "John",
        age: 21,
    },
    {
        name: "Max",
    },
];

function UserFunc(user: typeUsers) {
  // 给函数加上类型约束,避免传错参数
    if ("age" in user) {
        console.log(`Name: ${user.name}, Age: ${user.age}`);
    } else {
        console.log(`Name: ${user.name}`);
    }
}

// 遍历数组,逐个传入单个用户对象
Users.forEach(user => UserFunc(user));

也可以用普通的for循环:

for (let i = 0; i < Users.length; i++) {
  UserFunc(Users[i]);
}

另外建议给UserFunc的参数加上类型约束(user: typeUsers),这样TypeScript会帮你检查传入的参数类型,避免再出现传数组这种错误。

内容的提问来源于stack exchange,提问作者Oles Yudin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 00:54:29