函数检查给定整数数组中给定位置的元素是否大于其两个neigbours

时间:2013-11-21 16:04:31

标签: javascript

我在这里以及标题中添加我的问题: 函数检查给定整数数组中给定位置的元素是否大于其两个邻居。 这是我的示例代码:

`var dTest = new Array();

 dTest[0] = 1;
 dTest[1] = 2;
 dTest[2] = 3;
 dTest[3] = 4;
 dTest[4] = 5;

for (i=0;i<11;i++){

    if(dTest[i]>dTest[i+1] && dTest[i]>[i-1])

    {
        console.log("");
    }

    else 

    {
        console.log("");
    }

};`

所以我正在尝试的是用tittle写的。谢谢:)

2 个答案:

答案 0 :(得分:0)

对于初学者来说,由于某种原因,你的for循环一直持续到11(幻数?为什么11,这没有任何意义)。更改你的循环以运行数组的长度,然后检查一个数字是否存在于&#34; left&#34;或者&#34;对&#34;,如果是,那么做逻辑:

for (var i = 0; i < dTest.length; i++) {
    if (dTest[i-1] != undefined && dTest[i+1] != undefined) {
        //this position has neighbors!
        var current = dTest[i];
        if (current > dTest[i-1] && current > dTest[i+1]) {
            console.log(current + " is bigger than it's neighbors!");
        } else {
            console.log(current + " is smaller than it's neighbors!");
        }
    } else {
        console.log(dTest[i] + " doesn't have enough neighbors!");
    }
}

演示:http://jsfiddle.net/NFHTg/

答案 1 :(得分:0)

检查数组中不存在的索引时遇到问题。这个解决方案应该解决它:

for (var i = 0; i < dTest.length; i++) {
    if ((dTest[i-1] != undefined && dTest[i-1] > dTest[i]) ||
        (dTest[i+1] != undefined && dTest[i+1] > dTest[i])) {
         console.log('Element at position ' + i + ' is not bigger than his neighbours');
    } else {
         console.log('Element at position ' + i + ' is bigger than his neighbours');
    }
}