如何从循环中跳过每个第3个数字

时间:2018-01-08 06:50:22

标签: javascript angularjs loops

我想从逻辑跳过每三个数字,我累了,但我没有得到正确的方法。输出应该是这样的:0,1,3,4,6,7,9,10,12 ......

我试过这个,但它没有完全发挥作用。 **

for (var item = 0; item < $scope.gridImportData.data.length; item++)
{
  $scope.gridImportData[item] + (($scope.gridImportData[item] - 1) / 3)
}

**

6 个答案:

答案 0 :(得分:1)

试试这个

    angular.module("a",[]).controller("ac",function($scope){
    $scope.querylist =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
    $scope.newValue=[];
    for (var item = 0; item < $scope.querylist.length; item++){
    if($scope.querylist[item] % 3 == 0 && $scope.querylist[item] !=0)    {
        continue;
       }
      $scope.newValue.push($scope.querylist[item]);
    }

    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="a" ng-controller="ac">
    <table>
    <tr ng-repeat="x in newValue">
       <td>{{x}}</td>
    </tr> 
    </table>
    </div>

答案 1 :(得分:0)

怎么样:

for (var item = 0; item < 100; item++) {
  // skip every 3rd
  if ((item + 1) % 3 == 0) continue

  console.log(item)
}

答案 2 :(得分:0)

对余数运算符

使用if条件
for (var item = 0; item < $scope.gridImportData.data.length; item++)
{
  if(! (item % 3 === 2)){
    $scope.gridImportData[item] + (($scope.gridImportData[item] - 1) / 3)
  }
}

示例演示

var arr = [0,1,2,3,4,5,6,7,8,9,10,12]

for(let i=0; i<= arr.length-1; i++){
  if(! (i%3 === 2)){
     console.log(arr[i])
  }
}

答案 3 :(得分:0)

#include <stdio.h>
#include <stdlib.h>

int main()
{
int a[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14};
int n = sizeof(a)/sizeof(int);
int i, j = 2, count = 0;
printf("The are %d elements in the array\n", n);
for (i = 2; i<n ; i++)
{
if ((i)%3 != 2)
{
a[j] = a[i];
j++;
}
else
{
count++;
}
}
printf("Number of elements removed are : %d\n", count);
printf("Resultant array is\n");
for (i = 0; i < n - count; i++)
{
printf("%d ", a[i]);
}
printf("\n");

getch();
}

答案 4 :(得分:0)

这是你的循环,它会跳过3的所有乘法。

for (var i=0; i<25; i % 3 === 2 ? i = i + 2 : i++)
   console.log(i)

结果

0 1 2 4 5 7 8 10 11 13 14 16 17 19 20 22 23 

答案 5 :(得分:0)

假设你正在喂食一个阵列;您可以使用filterindexOf%来获得您的结果;

&#13;
&#13;
const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

let filteredNums = nums.filter((num) => (nums.indexOf(num)+1)% 3 != 0);

console.log(filteredNums)
&#13;
&#13;
&#13;