JavaScript循环获取最后一个循环

时间:2019-01-08 10:20:14

标签: javascript arrays for-loop

我有这样的数组:

[1,2,3,4,5,1,2,3,1,2,3]

我的问题我如何才能使数组仅获得最后一个循环,
它将变成这样:

[5,3,3]

我尝试这样,但是我混淆了,使情况发生

for(var i=0; i < arr.length; i++){
//how to make the looping just get bigger value before value 1
 console.log(arr[i]);
}

3 个答案:

答案 0 :(得分:1)

根据我的理解,您希望获得1值之间的数组中的最高值。

var arr = [1,2,3,4,5,1,2,3,1,2,3];
var highestValues = [];
var tempHighestValue = 0;

for(var x = 0; x < arr.length; x++){
   if(arr[x] > tempHighestValue)
      tempHighestValue = arr[x];

   if(arr[x+1] == 1 || arr[x+1] == undefined){
        highestValues.push(tempHighestValue);
        tempHighestValue = 0;
     }

}

console.log(highestValues);

答案 1 :(得分:0)

  

如何使循环在值1之前获得更大的值

在所有值n1 <= n的情况下,我们可以假定n大于n之前的任何数字。

这还假设1永远不会出现在1之前。

const data = [1,2,3,4,5,1,2,3,1,2,3];

const res = [];
for(let i = 0; i < data.length; i++){
  if(data[i] === 1 && i > 0){
     res.push(data[i-1]);
  }
}

console.log(res);

您的陈述也与您的输出相矛盾。

要使您的输出真实,我们可以假设,位置0处的1会取列表末尾的值。

const data = [1,2,3,4,5,1,2,3,1,2,3];

const res = [];
for(let i = 0; i < data.length; i++){
  if(data[i] === 1){
     res.push(data[(i-1 + data.length) % data.length]);
  }
}

console.log(res);

答案 2 :(得分:0)

您可以通过检查实际值旁边的元素来过滤局部最大值,或者在数组的开头或结尾忽略比较。

const
    data = [1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 3],
    localMaxima = data.filter((v, i, a) =>
        (a[i - 1] < v || i === 0) && (v > a[i + 1] || i + 1 === a.length));
    
console.log(localMaxima);