Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have a javascript function to find the index of an array like this

JavaScript
function myFunction() {
  var fruits = ["Lesson%202%20*,Lesson%203,Lesson%201%20*,"];
  var a = fruits.indexOf("Lesson%203");
  document.getElementById("demo").innerHTML = a;
}


this array always result in -1 which is wrong!!

while this function below
JavaScript
function myFunction() {
  var fruits = ["Banana", "Orange", "Apple", "Mango"];
  var a = fruits.indexOf("Apple");
  document.getElementById("demo").innerHTML = a;
}

return the index as 2 which is correct.

what I have been missing here can somebody explain the logic behind this?

What I have tried:

the code i have tried is shown above
Posted
Updated 8-Jul-19 5:25am
v3
Comments
CHill60 8-Jul-19 8:20am    
In your first example you only have a single entry in the array - compare where the quotes are between the two examples
Member 14052128 8-Jul-19 8:25am    
ok that was a typo i did while typing question sorry for that can u find any other error?
CHill60 8-Jul-19 8:44am    
I presume you still have a typo then - even after your correction you still only have a single string in that array. Do as @Dave-Kreskowiak suggests and paste your code into your question. It should be
var fruits = ["Lesson%202%20*","Lesson%203","Lesson%201%20*,"];

Hi,
There is basic typo while declaring fruits array. After correction:
function myFunction() {
  var fruits = ["Lesson%202%20*", "Lesson%203", "Lesson%201%20*,"];
  var a = fruits.indexOf("Lesson%203");
  document.getElementById("demo").innerHTML = a;
}

This returns 1. Which is as expected.
 
Share this answer
 
Comments
Member 14052128 8-Jul-19 23:44pm    
thankyou for correcting me :)
CHill60 9-Jul-19 7:12am    
Actually it was me that corrected you, 2 hours before this solution was posted!
You've got an array of only a single string and you're looking for a string entry in the array that doesn't match. You are expecting the IndexOf method to find substrings in the array elements and that's not what it does.

"Lesson%203" is not equal to "Lesson%202%20*,Lesson%203,Lesson%201%20*,".

As you said, this may be a typo. If it is, do NOT type the code. Copy and paste the EXACT code you're using.
 
Share this answer
 
Comments
Member 14052128 8-Jul-19 23:45pm    
yeah I found my mistake just like @anurag said

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900