javascript - 在数组中找到它的 2 个邻居之间的最小数字

标签 javascript arrays foreach

我想执行一个函数,最好是在 forEach 中,为每一个比第二个或倒数第二个数字高或相等的元素交出的每个元素,或者如果它的第一个或最后一个元素与第二个或倒数第二个数字相比。

我想出了这段代码,但我确信有更好的方法:

var Pointdata = [98,59,39,0,48,85,19,43,3,98,65,100];

    Pointdata.forEach(function(Current,i,array){

  if (Current <= array[i+1] && Current <= array[i-1]) {
  DrawPoint(Current,i,array);
  }
  else if (Current <= array[i+1] && i == 0) {
  DrawPoint(Current,i,array);
  }
  else if(Current <= array[i-1] && i+1 == array.length) {
  DrawPoint(Current,i,array);
  }

function DrawPoint(Current,i,array) { 
// marks peak points of canavas chart.
}

最佳答案

你可以在里面只使用一个条件,Current is a

if ((i + 1 === array.length || a <= array[i + 1]) && (i === 0 || a <= array[i - 1])) {
    DrawPoint(a, i, array);
}

关于javascript - 在数组中找到它的 2 个邻居之间的最小数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46060544/

相关文章:

javascript - 我如何在 CucumberJS 中跨多个步骤定义文件共享我的 World 实例?

javascript - javascript中应该使用什么正则表达式来匹配字符串中不包含两个点在一起

javascript - 未定义,它不计数,不工作为什么

c++ - 如何将字符串的第一个字符传递给char?

带步骤的 PowerShell 循环范围

PHP foreach : put each of the loop result in one variable

javascript - Node 缓冲区 : How to read out bit flags?

java - ArrayList 中存储的数组的逆序

c - c 中的段错误(核心转储)(将文本发送到数组)

php - 获取列内容作为数组键