我正在尝试检查数组中的给定元素是否大于它的两个相邻元素,但 array[element+1] 返回 - 未定义。但是,当我尝试使用 array1[(element-1)+2] 时,它工作得很好。
这是数组:
var array1 = [1, 5, 56, 6, 7, 8, 12, 5, 1];
我的代码:
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")
}
}
}
...以及用户接收元素的功能:
function assign(){
var i_element = document.getElementById('indexOfTheElement');
var i = i_element.value;
biggestOfThree(i)
}