Reputation: 35
I'm trying to check whether a given element in an array is bigger than it's two adjacent elements, but array[element+1] returns - undefined. However when I try with array1[(element-1)+2] it works just fine.
This is the array:
var array1 = [1, 5, 56, 6, 7, 8, 12, 5, 1];
And my Code:
function biggestOfThree(element){
if((element == 0)||(element == array1Length-1)){
document.write("There aren't 2 adjacent elements in the array");
}
else{
if((array1[element]>array1[element+1])&&(array1[element]>array1[element-1])){
document.write(array1[element] + " is bigger than it's adjacent elements")
}
else{
document.write(array1[element] + " isn't bigger than it's adjacent elements")
}
}
}
...and the function for receiving the element by the user:
function assign(){
var i_element = document.getElementById('indexOfTheElement');
var i = i_element.value;
biggestOfThree(i)
}
Upvotes: 2
Views: 112
Reputation: 46778
The error you see is due to JavaScript's dynamic typing. Use parseInt
var i = parseInt(i_element.value);
The + 1
still regards it a string and appends 1 to it. Performing a -1
forces it to consider it an int. Hence your results. Always convert to int using parseInt()
"1" + 1 = 11
"1" - 1 = 0
As @Elias said, it is best to define the radix when using parseInt.
parseInt(string, 10)
^ radix
Upvotes: 6