Javascript 在javascript中将NaN转换为0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7540397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:39:13  来源:igfitidea点击:

Convert NaN to 0 in javascript

javascript

提问by Tamás Pap

Is there a way to convert NaN values to 0 without an if statement:

有没有办法在没有 if 语句的情况下将 NaN 值转换为 0:

if (isNaN(a)) a = 0;

It is very annoying to check my variables every time.

每次都检查我的变量很烦人。

回答by user113716

You can do this:

你可以这样做:

a = a || 0

...which will convert a from any "falsey" value to 0.

...这会将 a 从任何“falsey”值转换为0.

The "falsey" values are:

“falsey”值是:

  • false
  • null
  • undefined
  • 0
  • ""( empty string )
  • NaN( Not a Number )
  • false
  • null
  • undefined
  • 0
  • ""(空字符串)
  • NaN(不是数字)


Or this if you prefer:

或者这个,如果你喜欢:

a = a ? a : 0;

...which will have the same effect as above.

...这将具有与上述相同的效果。



If the intent was to test for more than just NaN, then you can do the same, but do a toNumberconversion first.

如果意图不仅仅是测试NaN,那么您可以执行相同的操作,但首先进行toNumber转换。

a = +a || 0

This uses the unary + operator to try to convert ato a number. This has the added benefit of converting things like numeric strings '123'to a number.

这使用一元 + 运算符来尝试转换a为数字。这具有将数字字符串等内容转换为数字的额外好处'123'

The only unexpected thing may be if someone passes an Array that can successfully be converted to a number:

唯一出乎意料的可能是,如果有人传递了一个可以成功转换为数字的数组:

+['123']  // 123

Here we have an Array that has a single member that is a numeric string. It will be successfully converted to a number.

这里我们有一个数组,它有一个数字字符串成员。它将成功转换为数字。

回答by WickyNilliams

Using a double-tilde (double bitwise NOT) - ~~- does some interesting things in JavaScript. For instance you can use it instead of Math.flooror even as an alternative to parseInt("123", 10)! It's been discussed a lot over the web, so I won't go in why it works here, but if you're interested: What is the "double tilde" (~~) operator in JavaScript?

使用双波浪号 (double bitwise NOT) - ~~- 在 JavaScript 中做了一些有趣的事情。例如,您可以使用它来代替Math.floor甚至替代parseInt("123", 10)! 它在网络上已经讨论了很多,所以我不会在这里介绍它的工作原理,但是如果您有兴趣:JavaScript 中的“双波浪号”(~~) 运算符是什么?

We can exploit this property of a double-tilde to convert NaNto a number, and happily that number is zero!

我们可以利用双波浪号的这个特性来转换NaN为一个数字,很高兴这个数字为零!

console.log(~~NaN); // 0

console.log(~~NaN); // 0

回答by Saket

Write your own method, and use it everywhere you want a number value:

编写您自己的方法,并在需要数字值的任何地方使用它:

function getNum(val) {
   if (isNaN(val)) {
     return 0;
   }
   return val;
}

回答by woold Lucky

Something simpler and effective for anything :

对任何事情都更简单有效:

function getNum(val) {
   val = +val || 0
   return val;
}

...which will convert a from any "falsey" value to 0.

...这会将 a 从任何“falsey”值转换为0.

The "falsey" values are:

“falsey”值是:

  • false
  • null
  • undefined
  • 0
  • ""( empty string )
  • NaN( Not a Number )
  • false
  • null
  • undefined
  • 0
  • ""(空字符串)
  • NaN(不是数字)

回答by Chuck Kollars

Rather than kludging it so you can continue, why not back up and wonder why you're running into a NaN in the first place?

与其拼凑它以便您可以继续,为什么不备份并想知道为什么您首先遇到了 NaN 呢?

If any of the numeric inputs to an operation is NaN, the output will also be NaN. That's the way the current IEEE Floating Point standard works (it's not just Javascript). That behavior is for a good reason: the underlying intention is to keep you from using a bogus result without realizing it's bogus.

如果运算的任何数字输入为 NaN,则输出也将为 NaN。这就是当前 IEEE 浮点标准的工作方式(不仅仅是 Javascript)。这种行为是有充分理由的:潜在目的是防止您使用虚假结果而没有意识到它是虚假的。

The way NaN works is if something goes wrong way down in some sub-sub-sub-operation (producing a NaN at that lower level), the final result will alsobe NaN, which you'll immediately recognize as an error even if your error handling logic (throw/catch maybe?) isn't yet complete.

NaN 的工作方式是,如果在某些子子子操作中出现问题(在较低级别产生 NaN),最终结果将是 NaN,即使您的错误处理逻辑(可能是抛出/捕获?)尚未完成。

NaN as the result of an arithmetic calculation alwaysindicates something has gone awry in the details of the arithmetic. It's a way for the computer to say "debugging needed here". Rather than finding some way to continue anyway with some number that's hardly ever right (is 0 really what you want?), why not find the problem and fix it.

NaN 作为算术计算的结果总是表明算术细节出了问题。这是计算机说“此处需要调试”的一种方式。与其找到某种方法继续使用一些几乎永远不会正确的数字(0 真的是你想要的吗?),为什么不找到问题并解决它。

A common problem in Javascript is that both parseInt(...)and parseFloat(...)will return NaN if given a nonsensical argument (null, '', etc). Fix the issue at the lowest level possible rather than at a higher level. Then the result of the overall calculation has a good chance of making sense, and you're not substituting some magic number (0 or 1 or whatever) for the result of the entire calculation. (The trick of (parseInt(foo.value) || 0) works only for sums, not products - for products you want the default value to be 1 rather than 0, but not if the specified value really is 0.)

Javascript 中的一个常见问题是,如果给定一个无意义的参数(、 等),parseInt(...)parseFloat(...)都将返回 NaN 。在尽可能低的级别而不是在更高的级别解决问题。那么整体计算的结果很有可能是有意义的,并且您不会用一些幻数(0 或 1 或其他)代替整个计算的结果。( (parseInt(foo.value) || 0) 的技巧仅适用于总和,而不适用于产品 - 对于您希望默认值为 1 而不是 0 的产品,但如果指定值确实为 0,则无效。)null''

Perhaps for ease of coding you want a function to retrieve a value from the user, clean it up, and provide a default value if necessary, like this:

也许为了便于编码,您需要一个函数来从用户那里检索一个值,对其进行清理,并在必要时提供一个默认值,如下所示:

function getFoobarFromUser(elementid) {
        var foobar = parseFloat(document.getElementById(elementid).innerHTML)
        if (isNaN(foobar)) foobar = 3.21;       // default value
        return(foobar.toFixed(2));
}

回答by mplungjan

How about a regex?

怎么样一个正则表达式

function getNum(str) {
  return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;
}

The code below will ignore NaN to allow a calculation of properly entered numbers

下面的代码将忽略 NaN 以允许计算正确输入的数字

function getNum(str) {
  return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;
}
var inputsArray = document.getElementsByTagName('input');

function computeTotal() {
  var tot = 0;
  tot += getNum(inputsArray[0].value);
  tot += getNum(inputsArray[1].value);
  tot += getNum(inputsArray[2].value);
  inputsArray[3].value = tot;
}
<input type="text"></input>
<input type="text"></input>
<input type="text"></input>
<input type="text" disabled></input>
<button type="button" onclick="computeTotal()">Calculate</button>

回答by KARTHIKEYAN.A

var i = [NaN, 1,2,3];

var j = i.map(i =>{ return isNaN(i) ? 0 : i});


console.log(j)

[0,1,2,3]

[0,1,2,3]

回答by David Crowe

Methods that use isNaN do not work if you're trying to use parseInt, for example:

如果您尝试使用 parseInt,则使用 isNaN 的方法不起作用,例如:

parseInt("abc"); // NaN
parseInt(""); // NaN
parseInt("14px"); // 14

But in the second case isNaN produces false (i.e. the null string is a number)

但在第二种情况下 isNaN 产生假(即空字符串是一个数字)

n="abc"; isNaN(n) ? 0 : parseInt(n); // 0
n=""; isNaN(n) ? 0: parseInt(n); // NaN
n="14px"; isNaN(n) ? 0 : parseInt(n); // 14

In summary, the null string is considered a valid number by isNaN but not by parseInt. Verified with Safari, Firefox and Chrome on OSX Mojave.

总之,空字符串被 isNaN 视为有效数字,但不被 parseInt 视为有效数字。在 OSX Mojave 上通过 Safari、Firefox 和 Chrome 验证。

回答by subindas pm

Please try this simple function

请试试这个简单的功能

var NanValue = function (entry) {
    if(entry=="NaN") {
        return 0.00;
    } else {
        return entry;
    }
}

回答by webzy

using user 113716 solution, which by the way is great to avoid all those if-else I have implemented it this way to calculate my subtotal textbox from textbox unit and textbox quantity.

使用用户 113716 解决方案,顺便说一下,这很好地避免了所有这些 if-else 我已经通过这种方式实现了它,以根据文本框单元和文本框数量计算我的小计文本框。

In the process writing of non numbers in unit and quantity textboxes, their values are bing replace by zero so final posting of user data has no non-numbers .

在单位和数量文本框中写入非数字的过程中,它们的值被零替换,因此最终发布的用户数据没有非数字。

     <script src="/common/tools/jquery-1.10.2.js"></script>
     <script src="/common/tools/jquery-ui.js"></script>

     <!----------------- link above 2 lines to your jquery files ------>





    <script type="text/javascript" >
    function calculate_subtotal(){

    $('#quantity').val((+$('#quantity').val() || 0));
    $('#unit').val((+$('#unit').val() || 0));

    var  calculated = $('#quantity').val() * $('#unit').val() ;
    $('#subtotal').val(calculated);


    }
    </script>


      <input type = "text" onChange ="calculate_subtotal();" id = "quantity"/>
      <input type = "text" onChange ="calculate_subtotal();" id = "unit"/>
      <input type = "text" id = "subtotal"/>