强迫数字 [英] Coerce to number

查看:89
本文介绍了强迫数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在= +之后,我经常看到诀窍

I have often seen the trick

after = +after;

将后的变量强制转换为数字。通过 Node.JS来源阅读我发现了另一种方法:

to coerce the variable after to a number. Reading through the Node.JS source I found another method:

after *= 1; // coalesce to number or NaN

这两种方法的行为是否完全相同?

Are the two methods strictly equivalent in their behaviour?

推荐答案

是的。 一元运算符 + 复制运算符,例如 * (从复合赋值 op = )调用内部 ToNumber 算法。

Yes. Both Unary Operator + and Multiplicative Operators such as * (called from Compound Assignment op=) invoke the internal ToNumber algorithm.

您甚至可以静态使用第3个选项调用 Number 构造函数

You can even use a 3rd option by statically calling the Number constructor:

after = Number(after);

这篇关于强迫数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆