今天又看到一个新的 javascript 怪异笑话

2018-04-18 12:20:11 +08:00
 doubleflower
> parseInt(0.000001)
0

> parseInt(0.0000001)
1
6082 次点击
所在节点    JavaScript
26 条回复
ljsh093
2018-04-18 12:27:09 +08:00
F12 试了一下还真是
huiyifyj
2018-04-18 12:33:48 +08:00
👻诡异的 js😂
yangg
2018-04-18 12:38:40 +08:00
parseInt(string, radix)
If the string argument is not a string, then it is converted to a string (using the ToString abstract operation). Leading whitespace in the string argument is ignored.
String(0.000001)
String(0.0000001)

总想搞个大新闻。。。
murmur
2018-04-18 12:41:56 +08:00
@yangg 要点不是这个 是太长的小数自动转了科学计数法 这种坑不是每个人都记得到的
TtiGeR
2018-04-18 12:52:32 +08:00
所以 JavaScript 有那么多人爱啊 像个有个性有脾气的女孩 总是会有让你出乎意料的时候
Mutoo
2018-04-18 13:06:15 +08:00
MDN 文档里已经解释了 Because some numbers include the e character in their string representation (e.g. 6.022e23), using parseInt to truncate numeric values will produce unexpected results when used on very large or very small numbers.
muziki
2018-04-18 13:08:15 +08:00
这语言真烂
geelaw
2018-04-18 13:09:20 +08:00
因为这个用法不是 intended。如果你想把浮点数变换为整数,你可以使用 Math.floor/ceil/round/trunc,当然结果还是浮点数。
SourceMan
2018-04-18 13:17:20 +08:00
说这语言真烂的,楼下是不是也搞个其他语言的示例出来
DOLLOR
2018-04-18 13:53:33 +08:00
日常黑动态类型语言。

parseInt(string, radix)
第一个参数是 String,你非要传一个 Number 进去,造成不可预知问题,怪我咯?
SuperMild
2018-04-18 13:55:04 +08:00
烂没关系,它命好啊,时来运转,不优秀照样能混得风生水起。

其实 Javascript 也有很多优点,表现力很强,很灵活,用来写小东西很方便,而这正符合这个语言本来的目的,因此可以说语言设计是成功的。
hjdtl
2018-04-18 13:57:26 +08:00
已经 8102 年了,为什么还有这样的帖子。。。
orangeade
2018-04-18 14:06:13 +08:00
@DOLLOR #9
python 也是动态语言,然而
>>> int(0.000001)
0
>>> int(0.0000001)
0

int(x, base=10)
Convert a number or string x to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base.


明明是设计问题
doubleflower
2018-04-18 14:09:43 +08:00
@DOLLOR JS 是弱类型,很多错误会被掩盖,python 同样是动态类型它是强类型,碰到不合理的错误会报错
这是先天设计问题,只能靠 ts 之类的来救了
zhuangzhuang1988
2018-04-18 14:20:14 +08:00
typescript 检查开起来 直接报错
wengjin456123
2018-04-18 15:45:56 +08:00
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). 了解一下?
wbgbg
2018-04-18 16:01:06 +08:00
我不看接口文档,我想传什么类型就传什么类型,结果不符合我的心意就是接口的问题 :doge:
Pastsong
2018-04-18 16:04:49 +08:00
想看奇技淫巧吗 :doge:

~~0.000001
> 0
~~0.0000001
> 0
seancheer
2018-04-18 16:49:40 +08:00
@doubleflower 弱类型真不是可以出现这种奇葩问题的理由,想起 js 那个== != 的表格,连数学里最基本的传递性都能出问题,各种奇葩问题表明这语言从设计之初就很随意。。楼上说的很对,js 确实命好,赶上了移动互联网,这要是换其他语言这不严谨早死一万遍了。
beny2mor
2018-04-18 17:36:46 +08:00
parseInt:你传了个 String 怪我喽?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/447770

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX