Talk:Core JavaScript 1.5 Reference:Global Objects:Array:indexOf
From MDC
"If the index is greater than the length of the array, the length of the array will be used." That sounds wrong. Should it say, "If the index is greater than the length of the array, the greatest index in the array will be used."? --Jonnyq
- Um, unless I'm missing something, it's saying that if
fromIndex >= array.length,-1will be returned. - Your variant is rather unclear, but I think it means, that the index of last element will be returned, when the last element is === the value being searched. Where "last element" means "the element with the greatest index", whatever "greatest index" means. -Nickolay 02:13, 3 October 2005 (PDT)
- I can confirm that if
fromIndex >= array.length, -1 is returned. However, I can't get a negative fromIndex value working.[1, 2, 3, 4].indexOf(4, -3)still returns 3. Bug? Or is the doc here wrong? --Maian 03:20, 3 October 2005 (PDT)- Negative indices seem very buggy to me, and I couldn't find any bug about that. I think you should file one. --Nickolay 05:45, 3 October 2005 (PDT)
- Okay it was a misunderstanding. I was assuming that a negative value would make the indexOf work like lastIndexOf, but it doesn't. So
[1, 2, 3, 4].indexOf(4, -3)starts searching at index 1 (length - 3), so it tries to find 4 in the subset [2, 3, 4]. I'll update the article to clarify this. BTW, if this isn't what you mean, what did you mean by "very buggy"? --Maian 06:28, 3 October 2005 (PDT)- Yes. It did look buggy :) --Nickolay 10:31, 3 October 2005 (PDT)
- Okay it was a misunderstanding. I was assuming that a negative value would make the indexOf work like lastIndexOf, but it doesn't. So
- Negative indices seem very buggy to me, and I couldn't find any bug about that. I think you should file one. --Nickolay 05:45, 3 October 2005 (PDT)
- I can confirm that if
- Nickolay understood what I was saying, but didn't exactly answer my question. The page says, "If the index is greater than the length of the array, the length of the array will be used." Maian is correct, if the
fromIndex >= Array.lengtha -1 is always returned. While it may be programmatically true that "... the length of the array is used," that's moot - the returned value will be-1regardless. Maybe the page should reflect this. Maybe it should say "If the index is greater than the length of the array,-1will be returned." --[[User:Jonnyq|Jonnyq]- As a JavaScriptCore hacker, I ran into this problem to doing testcases to see how our implementation of this function was going to work. This oversight actually confused at first, then we realised it always returned -1, and guess what? We always return -1, and the support code to help us do this was very easy to write.