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);

17th Nov 2018, 10:48 PM
Anuluxmy
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);
19th Nov 2018, 10:07 AM
Rishi Anand
Rishi Anand - avatar
0
you must return: haystack[i].indexOf("needle") but you return only text. so add haystack[i].indexOf("needle") in your return
17th Nov 2018, 10:56 PM
_yaroslavv [online_everyday]
_yaroslavv [online_everyday] - avatar
0
but how do i add text which should output fiund the needle at position x
18th Nov 2018, 8:07 AM
Anuluxmy