Code:
function showlayer(name){
var size = js_array.length
var index = js_array.indexOf(name);
var plusOne = js_array[index+1];
document.write("" + name + "<br />" + js_array + "<br />" + index + "<br />" +
plusOne + "<br />" )
...
}
Output:
301
300,299,301,290,303,304,302,310,291,306,308,305,307,292,294,295,309
-1
300
All possible values of name are in the array, but for some reason indexOf() never finds them. Whats up?
indexOf() 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.
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.
Definition and Usage The indexOf() method returns the first index (position) of a specified value. The indexOf() method returns -1 if the value is not found. The indexOf() method starts at a specified index and searches from left to right. By default the search starts at the first element and ends at the last.
Yes, technically array-indexes are strings, but as Flanagan elegantly put it in his 'Definitive guide': "It is helpful to clearly distinguish an array index from an object property name. All indexes are property names, but only property names that are integers between 0 and 232-1 are indexes."
Try this instead:
...
var index = js_array.indexOf(parseInt(name, 10)); // so that it does not try to compare strings...
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With