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
598 views
in Technique[技术] by (71.8m points)

value = +value; 有什么作用呢?

在MDN上学习js,看到Math.round方法有个对一个数取小数点后x位的四舍五入方法
其中有一句value = +value;不明白其原理及作用

MDN Decimal rounding的16行

补充问题:上面链接Decimal rounding 的19行如是写
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))

是否这样写更简单明了?
if (isNaN(value) || typeof exp === 'number' || exp % 1 === 0)


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

1 Answer

0 votes
by (71.8m points)
  1. 要解读 value = +value 的含义,需要知道js是一门弱类型语言,js的变量间可以相互转换类型。比如:字符串'11'可以被转化为数字11,反向也可转换。所以, value = +value是对变量value做了类型转换,使用加号运算来将value转化为数字类型(number)。

  2. if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) 这句的逻辑不能改为if (isNaN(value) || typeof exp === 'number' || exp % 1 === 0)。这是的组合使用,应该不需要过多解释,多思考一下就懂了。


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

...