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

如何统计JavaScript数组中符合断言条件的元素数量?含简洁实现问询

Counting Elements Matching a Predicate in JavaScript (e.g. NaNs in an Array)

Great question! Let's break down cleaner ways to count elements that meet a specific condition in JavaScript, using your NaN-counting use case as an example.

First, recap your test array setup—you created 100 elements with a NaN every 10 items:

let arr = [...Array(100)].map( (a,i) => i % 10 === 0 ? NaN : i )

Your initial map() + reduce() approach works, but as you noticed, it’s a bit verbose:

let nans = arr.map( aa => isNaN(aa) ? 1 : 0).reduce((acc,a) => acc+a)

Simpler, More Expressive Approaches

1. filter() + .length (Most Readable)

The easiest shortcut is to filter the array for matching elements, then grab the length of the resulting array. This is intuitive and concise:

const nanCount = arr.filter(item => isNaN(item)).length;

This returns the same result (10) with far less boilerplate.

2. Add a Custom count() Method (Your Desired Syntax)

If you want to use something like arr.count(a => isNaN(a)) directly, you can extend the Array prototype with a custom count method. This makes your code more expressive and reusable:

// Extend Array prototype with a count method
Array.prototype.count = function(predicate) {
  // Use reduce for efficiency (no intermediate array is created)
  return this.reduce((accumulator, currentItem) => {
    return predicate(currentItem) ? accumulator + 1 : accumulator;
  }, 0);
};

// Now use it exactly how you wanted!
const nanCount = arr.count(item => isNaN(item));

Note: Extending native prototypes can cause conflicts in large projects or with third-party libraries. If you’re concerned about this, use a standalone utility function instead:

function count(arr, predicate) {
  return arr.reduce((acc, item) => predicate(item) ? acc + 1 : acc, 0);
}

// Usage:
const nanCount = count(arr, item => isNaN(item));

A Quick Caveat About isNaN

The global isNaN() function returns true for values like undefined or empty strings (since it coerces values to numbers first). To strictly count only actual NaN values, use Number.isNaN() instead:

const strictNanCount = arr.count(item => Number.isNaN(item));

Number.isNaN() only returns true if the input is exactly the NaN value, avoiding false positives.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:11:36