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

JavaScript:处理数字列表及函数非数字入参时如何返回NaN

Question 2: How to make a number-focused function return NaN for non-numeric inputs?

For functions designed for operations like multiplication, validating inputs upfront is key. Here are robust approaches:

Method 1: Strict type checking

This ensures only actual finite numbers are processed. Return NaN if any input isn’t a valid number type:

function multiply(a, b) {
  // Check if both inputs are finite numbers
  if (typeof a !== "number" || !Number.isFinite(a) || 
      typeof b !== "number" || !Number.isFinite(b)) {
    return NaN;
  }
  return a * b;
}

// Test cases
multiply(2, 3); // 6
multiply("2", 3); // NaN (string isn't a number type)
multiply(5, NaN); // NaN (NaN isn't a finite number)

Method 2: Allow safe coercion

If you want to accept values that can be safely converted to numbers (like string "4" or boolean true), convert inputs first and check for NaN:

function multiply(a, b) {
  const numA = Number(a);
  const numB = Number(b);
  
  // Return NaN if either conversion fails
  if (Number.isNaN(numA) || Number.isNaN(numB)) {
    return NaN;
  }
  return numA * numB;
}

// Test cases
multiply("4", 5); // 20 (string coerces to number)
multiply(true, 6); // 6 (true coerces to 1)
multiply("foo", 3); // NaN (can't coerce "foo" to number)

Key Tip:

Use Number.isNaN() instead of the global isNaN()—the global version tries to convert non-number values to numbers first, leading to false positives (e.g., isNaN("foo") returns true even though "foo" isn’t NaN). Number.isNaN() only returns true if the value is actually NaN.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 20:03:15