看到一段代码用id大小比较两条记录的创建时间,结果出现了一些bug。

["38","378","379","380"].filter(ele => {return ele >= "378" && ele <= "380"})
//result ["38","378","379","380"]

本意是筛掉38这个情况,但是因为字符串在js中比较大小并不是比较其数字的大小,而是逐字符比较数字的编码大小。

38 > "378" //false
"38" > "378" //true

这种情况应该parseInt转换成numeric的类型再比较大小

Last modified: 06/04/2023

Author

Comments

Write a Reply or Comment

Your email address will not be published.