You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery/JavaScript或AngularJS统计指定区间的DisciplineId数量?

嘿,这个区间统计的需求很常见,我给你分别用三种方式实现,你可以根据自己的项目环境来选~

原生JavaScript实现

这是最通用的方式,不管你用不用框架都能直接用:

// 假设你的DisciplineId数据是这样的数组(如果是从后端接口拿的,直接替换成你的数据即可)
const disciplineData = [
  { DisciplineId: 10 },
  { DisciplineId: 20 },
  { DisciplineId: 30 },
  { DisciplineId: 71 },
  { DisciplineId: 81 }
];

// 初始化三个区间的计数器
let countBelow70 = 0;
let count70To80 = 0;
let countAbove81 = 0;

// 遍历数据做统计
disciplineData.forEach(item => {
  const id = item.DisciplineId;
  if (id < 70) {
    countBelow70++;
  } else if (id >= 70 && id <= 80) {
    count70To80++;
  } else if (id > 81) {
    countAbove81++;
  }
});

// 输出结果,也可以把这些值渲染到页面上
console.log(`小于70的数量:${countBelow70}`); // 3
console.log(`70-80区间的数量:${count70To80}`); // 1
console.log(`大于81的数量:${countAbove81}`); // 1

jQuery实现

如果你的项目已经在用jQuery,用它的遍历方法也能轻松搞定,逻辑和原生基本一致:

// 同样假设数据数组
const disciplineData = [
  { DisciplineId: 10 },
  { DisciplineId: 20 },
  { DisciplineId: 30 },
  { DisciplineId: 71 },
  { DisciplineId: 81 }
];

let countBelow70 = 0;
let count70To80 = 0;
let countAbove81 = 0;

// 用jQuery的$.each遍历数据
$.each(disciplineData, function(index, item) {
  const id = item.DisciplineId;
  if (id < 70) {
    countBelow70++;
  } else if (id >= 70 && id <= 80) {
    count70To80++;
  } else if (id > 81) {
    countAbove81++;
  }
});

// 查看结果
console.log(`小于70:${countBelow70}`);
console.log(`70-80:${count70To80}`);
console.log(`大于81:${countAbove81}`);

AngularJS(1.x)实现

如果是AngularJS 1.x的项目,可以在控制器里处理统计,还能直接把结果绑定到视图上:

angular.module('myApp', [])
.controller('DisciplineController', function($scope) {
  // 定义你的DisciplineId数据
  $scope.disciplineData = [
    { DisciplineId: 10 },
    { DisciplineId: 20 },
    { DisciplineId: 30 },
    { DisciplineId: 71 },
    { DisciplineId: 81 }
  ];

  // 初始化统计结果对象
  $scope.stats = {
    below70: 0,
    between70And80: 0,
    above81: 0
  };

  // 用angular.forEach遍历统计
  angular.forEach($scope.disciplineData, function(item) {
    const id = item.DisciplineId;
    if (id < 70) {
      $scope.stats.below70++;
    } else if (id >= 70 && id <= 80) {
      $scope.stats.between70And80++;
    } else if (id > 81) {
      $scope.stats.above81++;
    }
  });

  // 也可以用数组的reduce方法更简洁地实现
  /*
  $scope.stats = $scope.disciplineData.reduce((acc, item) => {
    const id = item.DisciplineId;
    if (id < 70) acc.below70++;
    else if (id >= 70 && id <= 80) acc.between70And80++;
    else if (id > 81) acc.above81++;
    return acc;
  }, { below70: 0, between70And80: 0, above81: 0 });
  */
});

在HTML视图里,你可以直接这样显示统计结果:

<div ng-app="myApp" ng-controller="DisciplineController">
  <p>小于70的数量:{{stats.below70}}</p>
  <p>70-80区间的数量:{{stats.between70And80}}</p>
  <p>大于81的数量:{{stats.above81}}</p>
</div>

内容的提问来源于stack exchange,提问作者Abdul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:03:42