这里是新手。我从 1 周前开始学习一些编码。我的代码遇到了问题。我只想打印分数大于 4 的雇主姓名。
这是我的代码:
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) {
let List = [employers];
for (let i = 0; i < List.length; i++) {
if(List['score'] > 4 ) {
return List[i].name;
}
}
}
console.log(getEmployer(employers))
你能给我一些细节吗?
这是我的做法,与您的做法类似。请参阅各行旁边的注释以获取解释。
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) {
let list = []; // Empty array to store the results in.
for (let i = 0; i < employerList.length; i++) { // Loop over the items in 'employerList',
if(employerList[i].score > 4 ) {
list.push(employerList[i]); // Add the item from employerList to the array with results.
}
}
return list; // Return the array with results.
}
console.log(getEmployer(employers))
当您可以使用
for
时,无需在此处使用 forEach
循环 - 您可以直接循环遍历作为参数传递给函数的数组。
此外,还添加了一个数组来保存多个数组元素,其中
score
大于 4
。
const employers = [{
name: "Adam",
score: 5
},
{
name: "Jane",
score: 3
},
{
name: "Lucas",
score: 3
},
{
name: "Francesca",
score: 5
},
{
name: "Mason",
score: 4
}
]
function getEmployer(employerList) {
// Let's have a holder for all that are greater than 4.
let highScore = [];
// Make sure you are actually passing an array.
if (Array.isArray(employerList)) {
// Loop through what is passed.
employerList.forEach((elem) => {
// If the array element score is greater than 4, let's push it into our highScore array.
if (elem.score > 4) {
highScore.push(elem);
}
});
}
// Return it!
return highScore;
}
console.log(getEmployer(employers));
在代码的这一部分
let List = [employers];
,您将数组参数放入不需要的数组中,并且没有在 if 中传递索引。您可以通过这种方式修复您的代码,但是此解决方案将仅打印第一个匹配项
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;
}
}
}
console.log(getEmployer(employers))
您可以通过这种方式返回雇主数组以显示所有匹配项
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: "Francesca2", score: 2 },
{ name: "Mason2", score: 7 }
]
function getEmployer(employerList) {
let matchedEmployers = [];
employerList.forEach((employer) => {
if(4 < employer.score) {
matchedEmployers.push(employer.name)
}
})
return matchedEmployers;
}
console.log(getEmployer(employers))