




本文教你如何正确遍历对象数组、筛选满足条件(如 score > 4)的元素,并返回所有匹配员工姓名,同时指出新手常见的数组嵌套与属性访问错误。
在 JavaScript 中,处理包含对象的数组(如员工信息列表)是基础但关键的技能。初学者常因混淆数据结构层级、错误访问属性或过早 return 而无法获得预期结果。下面我们将从你原始代码的问题出发,逐步讲解正确实现方式。
const employers = [
{ name: "Adam", score: 5 },
{ name: "Jane", score: 3 },
{ name: "Lucas", score: 3 },
{ name: "Francesca", score: 2 },
{ name: "Mason", score: 4 }
];
function getEmployer(employerList) {
for (let i = 0; i < employerList.length; i++) {
if (employerList[i].score > 4) { // ✅ 直接访问对象属性,无需引号
return employerList[i].name; // ⚠️ 仅返回第一个匹配项
}
}
return null; // ✅ 建议添加兜底返回值,避免 undefined
}
console.log(getEmployer(employers)); // 输出: "Adam"? 提示:此写法适用于“找一个即可”的场景,但不满足“打印所有高分员工”的原始需求。
更符合实际业务逻辑——收集所有 score > 4 的员工姓名:
function getEmployer(employerList) {
const matchedNames = []; // ✅ 使用语义化变量名
employerList.forEach(employer => {
if (employer.score > 4) {
matchedNames.push(employer.name);
}
});
return matchedNames;
}
// 测试数据(含多个高分员工)
const employers = [
{ name: "Adam", score: 5 },
{ name: "Jane", score: 3 },
{ name: "Lucas", score: 3 },
{ name: "Francesca", score: 2 },
{ name: 
"Mason", score: 4 },
{ name: "Lucas2", score: 8 },
{ name: "Mason2", score: 7 }
];
console.log(getEmployer(employers));
// 输出: ["Adam", "Lucas2", "Mason2"]✅ 优势:
const getEmployer = (list) => list .filter(emp => emp.score > 4) .map(emp => emp.name); console.log(getEmployer(employers)); // ["Adam", "Lucas2", "Mason2"]
✅ filter() + map() 组合是处理此类“筛选→提取”任务的标准函数式范式,代码更声明式、无副作用。
掌握数组与对象的协同操作,是你迈向 JavaScript 数据处理能力的关键一步。从理解结构、修正语法,到选择合适的方法(for / forEach / filter+map),每一步都值得反复练习。