0
javascript
can someone correct me where am i wrong in writing this code. to find needle in haystack using for loop and return found the needle in position x. x being the index number. var haystack =[“hay”, “needle”, “ rabbit”, “hat”]; for (i=o;i<=haystack.length;i++){ console.log(haystack[i]); } function findNeedle(haystack){ return “found needle at position” haystack[i].indexOf (“needle”); } findNeedle(haystack);
3 Antworten
+ 2
1. you forgot to put the keyword var inside forloop
2. you are assigning i=o instead of i=0 (i.e.zero)
3. you are running the loop 5 times instead of 4
4. return statement should contain + operator
5. haystack.indexOf("needle") should be used
6. you are returning index not position
position=index +1
//this the correct way of doing
var haystack=["hay","needle","rabbit","hat"];
for(var i=0;i<haystack.length;i++)
{
console.log(haystack[i]);
}
function findNeedle(haystack)
{
return "found needle at index"+haystack.indexOf("needle");
}
findNeedle(haystack);
0
you must return: haystack[i].indexOf("needle")
but you return only text.
so add haystack[i].indexOf("needle") in your return
0
but how do i add text which should output
fiund the needle at position x