Number.isFinite Rejects String Coercion
The global isFinite coerces its argument first, so quoted numbers and null pass; Number.isFinite accepts only genuine finite numbers.
Code
// 全局 isFinite 先把参数转成数字再判断:字符串数字、null、true、'' 全部放行
console.log('global isFinite :', [42, '42', null, true, ''].map((v) => isFinite(v)));
// Number.isFinite 不做转换:只有真正的有限 number 才算数
console.log('Number.isFinite :', [42, '42', null, true, ''].map((v) => Number.isFinite(v)));
// 计数字段的白名单校验:整数且非负,其余形态一律拒绝
function isCount(value) {
return Number.isInteger(value) && value >= 0;
}
console.log('isCount checks :', [3, '3', 1.5, -1].map((v) => isCount(v)));
// NaN 与 Infinity 的常见来源同样被拒之门外
console.log('NaN from Number("x"):', Number.isFinite(Number('x')));
console.log('Infinity from 1/0 :', Number.isFinite(1 / 0));Output
Captured from a sandboxed run of this snippet in the build pipeline.
global isFinite : [ true, true, true, true, true ]
Number.isFinite : [ true, false, false, false, false ]
isCount checks : [ true, false, false, false ]
NaN from Number("x"): false
Infinity from 1/0 : falseHow it works
Number.isFinite Rejects String Coercion is built around the function isCount.
Putting it to use
The primary signature is function isCount(value)
Running the file prints labeled results such as global isFinite :, Number.isFinite :, isCount checks : — each operation’s effect is visible in the output.
Core lines
return Number.isInteger(value) && value >= 0;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `isCount` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.