0
JavaScript Problem (array, const, indexOf)
The problem is... const array = [1, 2, 3, 5]; const result = array.indexOf(3); The answer comes out to 2. The explanation is: JavaScript arrays are zero-indexed: the first element of an array is at index 0 (I understand this part), and the last element is at the index equal to the value of the array's length property value minus 1 (huhhh?). The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. ______________ Can someone explain this to me in layman's terms or like I'm 5 years old? Lol
9 Respuestas
+ 3
Not quite bro, okay let's look again at the array ...
👇
INDEX 0 1 2 3
VALUE 1 2 3 5
const result = array.indexOf(3);
Here we ask Javascript "give me the index of an element whose value equal to 3". So Javascript try to find that one element having value equal to 3, and it turned out that the element having value 3 is positioned at index 2. In above example the index is pointed by finger ponting down -> 👇
That's how it works bro Zone ...
+ 8
Let's look at the array ...
INDEX 0 1 2 3*
VALUE 1 2 3 5
Value of `length` property for the above array would be 4 because there are 4 elements contained in. And if you notice, index of the last element in the array is 3 (marked by *) which is value of `length` property (4) minus 1.
`indexOf` method returns -1 when a value you try to find does not exist in the array.
+ 4
Ipang As always... excellent, clear and concise, explanations.
Zone I just reviewed your history and wanted to say keep at it. I get the sense you might be close to reaching that point when things begin to click.
Moments like this where you catch yourself "over thinking" and you realize it with clarity are a strong indication you're on the cusp.
Feel free to ping me by name as well if you ever want me to chime in on a question you have. I'm always happy to help people in your stage - break through to the next level.
+ 3
No problem Zone 👌
+ 1
Ipang thanks 👍🏽
+ 1
Bro, DM doesn't work, my replies are stuck not getting sent, but I can read ...
About length property of string, it returns the number of character contained in a string. So for string "SoloLearn", length is 9. And for string "Javascript" length is 10.
This has nothing to do with indices ...
+ 1
David Carroll it's funny cuz this week I've actually started feeling frustrated again. Again, I'm probably just overthinking things. Thanks. I find that doing quizzes often helps me get out of that discouraging funk.
0
Ipang I'm revisiting this problem again.. so is the reason why the answer is 2 is because it's doing 5 (value) - 3 (index) ?
0
Ipang oh wow, I was just overthinking it 😅 thanks again 🙌🏽