JavaScript中统计数组元素在指定数值区间内的数量
统计数组元素在指定区间的数量
需求:统计计算得到的数组const C中落在指定数值区间内的元素数量。例如当数组C为[2,2,1.5,1.5]时,需分别统计x<1、1<x<2、x>2这三个区间的元素数量,预期结果为:x<1的数量是0,1<x<2的数量是4,x>2的数量是0。
当前代码:
for(let i = 0; i < 1; i++) { Array.prototype.zip = function (other, reduce, thisArg) { var i, result = [], args, isfunc = typeof reduce == "function", l = Math.max(this.length, other.length); for (i = 0; i < l; i++) { args = [ this[i], other[i] ]; result.push( isfunc ? reduce.apply(thisArg, args) : args ); } return result; } const A = [4,6,12,18] const B = [2,3,4,6] const C = A.zip(B, function (l, r) { return l / (l - r); }); //[2,2,1.5,1.5] let id = document.querySelectorAll(`[id^="id"]`)[i] let problemTypeChoice = 0; if (problemTypeChoice === 0) { id.innerText = `${C}` } }
解决方案
可以用数组的reduce方法一次性统计三个区间的元素数量,同时注意不要在循环内重复定义Array.prototype.zip(把它移到循环外避免冗余),修改后的代码如下:
// 把zip方法定义在循环外,避免重复创建 Array.prototype.zip = function (other, reduce, thisArg) { var i, result = [], args, isfunc = typeof reduce == "function", l = Math.max(this.length, other.length); for (i = 0; i < l; i++) { args = [ this[i], other[i] ]; result.push( isfunc ? reduce.apply(thisArg, args) : args ); } return result; } for(let i = 0; i < 1; i++) { const A = [4,6,12,18] const B = [2,3,4,6] const C = A.zip(B, function (l, r) { return l / (l - r); }); //[2,2,1.5,1.5] let id = document.querySelectorAll(`[id^="id"]`)[i] let problemTypeChoice = 0; if (problemTypeChoice === 0) { // 统计各区间数量 const count = C.reduce((acc, num) => { if (num < 1) { acc.lessThan1++; } else if (num > 1 && num < 2) { acc.between1And2++; } else if (num > 2) { acc.greaterThan2++; } // 注意:如果num等于1或2,这里没有统计,根据需求可调整 return acc; }, { lessThan1: 0, between1And2: 0, greaterThan2: 0 }); // 格式化输出结果 id.innerText = `x<1的数量:${count.lessThan1},1<x<2的数量:${count.between1And2},x>2的数量:${count.greaterThan2}`; } }
关键点说明
- 将
Array.prototype.zip移到循环外部,避免每次循环都重新定义方法,提升性能 - 使用
reduce遍历数组C,通过累加器对象acc分别统计三个区间的元素数量 - 输出部分直接展示统计后的结果,符合需求中的预期格式
- 代码中忽略了
num === 1和num === 2的情况,如果需要统计这两个边界值,可以根据实际需求调整判断条件
内容的提问来源于stack exchange,提问作者evan2160
相关产品推荐
相关产品推荐

