Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

javascript - 在javascript中将NaN转换为0(Convert NaN to 0 in javascript)

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.(每次检查我的变量都非常烦人。)   ask by Tamás Pap translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do this:(你可以这样做:)

a = a || 0 ...which will convert a from any "falsey" value to 0 .(...这会将a的任何“ falsey”值转换为0 。) The "falsey" values are:(“假”值是:) false null undefined 0 "" ( empty string )("" (空字符串)) NaN ( Not a Number )(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 toNumber conversion first.(如果要测试的不仅仅是NaN ,则可以执行相同的操作,但首先进行toNumber转换。) a = +a || 0 This uses the unary + operator to try to convert a to a number.(这使用一元+运算符尝试将a转换为数字。) This has the added benefit of converting things like numeric strings '123' to a number.(这具有将数字字符串'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.(它将成功转换为数字。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...