如何解决挑战:使用 forEach
我在 forEach 函数的语法和应用方面遇到了很多麻烦。请帮忙!
重新创建上一个挑战中的函数 droids,但不要使用 FOR 循环,而是使用内置的 forEach 方法。
之前的挑战:
function droids(arr) {
let result = '';
for (let str of arr) {
if (str === 'Droids') {
return 'Found Droids!';
}
}
return `These are not the droids you're looking for.`;
}
// Uncomment these to check your work!
const starWars = ["Luke","Finn","Rey","kylo","Droids"]
const thrones = ["Jon","Danny","Tyrion","The Mountain","Cersei"]
console.log(droids(starWars)) // should log: "Found Droids!"
console.log(droids(thrones)) // should log: "These are not the droids you're looking for."
这就是我所拥有的:
function droids(arr) {
let result = "";
arr.forEach(item =>
console.log(result))
if (result = "Droids") {
return "Found Droids!"
} else {
return "These are not the droids you're looking for.";
}};
解决方法
您无法在 forEach
循环中从回调中返回值,因此您需要依赖副作用 - 给 result
一个默认值,表示您没有找到 {{1} } 然后将它设置为 Droids
仅当您匹配数组中某处的 "Found Droids!"
时:
Droids
if (result = "Droids")
这不检查,它分配。您想使用 ==
。
您不想从 forEach
方法内部返回。您需要分配结果并在处理记录后返回该结果。
请务必将项目与您要查找的字符串值进行比较。
function droids(arr) {
let result = "";
let foundDroids = false;
arr.forEach(item => {
if (!foundDroids) {
if (item == "Droids") {
result = "Found Droids!"
foundDroids = true;
} else {
result = "These are not the droids you're looking for.";
}
}
});
return result;
};
const starWars = ["Luke","Finn","Droids","Rey","Kylo"]
const thrones = ["Jon","Danny","Tyrion","The Mountain","Cersei"]
console.log(droids(starWars))
console.log(droids(thrones))
我更愿意像这样使用 Array.includes:
function droids(arr) {
if (arr.includes("Droids")) {
return "Found Droids!";
} else {
return "These are not the droids you're looking for.";
}
};
const starWars = ["Luke","Cersei"]
console.log(droids(starWars))
console.log(droids(thrones))
我不会使用 Array.prototype.forEach
,而是使用 Array.prototype.some
来确定该项目是否存在。
some
与 forEach
方法具有相同的签名,只是您需要返回一个布尔值。如果您返回 true
,该方法将在找到匹配项后立即短路并停止迭代。性能更好。
const search = (items,target,foundText,notFoundText) =>
items.some(item => item === target) ? foundText : notFoundText;
const droids = (names) => search(names,'Droids','Found Droids!',"These are not the droids you're looking for.");
// Uncomment these to check your work!
const starWars = ["Luke","Kylo","Droids"]
const thrones = ["Jon","Cersei"]
console.log(droids(starWars)) // "Found Droids!"
console.log(droids(thrones)) // "These are not the droids you're looking for."
由于这是一个原始数组,您也可以使用 Array.prototype.includes
。
const search = (items,notFoundText) =>
items.includes(target) ? foundText : notFoundText;
const droids = (names) => search(names,"Cersei"]
console.log(droids(starWars)) // "Found Droids!"
console.log(droids(thrones)) // "These are not the droids you're looking for."
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。