I have been given the task of creating a function that iterates through an array. Below is what I have, but I’m getting undefined
. What am I missing?
function lookingForDave(arr) {
for (var i = 0; i < arr; i++) {
if (array.forEach === 'Dave') {
return 'I found him';
} else {
return 'Not Dave';
}
}
}
var testArray = ['Dave'];
console.log(lookingForDave(testArray));
You could use find rather than a for loop. It looks as if you want to return after you first find a match. Array.find will return the value of the first matching criteria.
In the below case if the element in the array is equal to Dave. If there is no match then we will iterate through each item in the array and return undefined.
We can then use the conditional (ternary) operator to test if an item was found.
function lookingForDave (arr){
const found = arr.find(el => el === 'Dave');
return found ? 'found him' : 'Not Dave';
}
let testArray = ['Dave'];
lookingForDave(testArray);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加