且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串转换为javascript中的数字

更新时间:2023-02-03 07:54:26

我用 Number(x),如果我必须在这两者之间做出选择,因为它不允许尾随垃圾。 (好吧,它允许它,但结果是 NaN 。)

I'd use Number(x), if I had to choose between those two, because it won't allow trailing garbage. (Well, it "allows" it, but the result is a NaN.)

数字(123.45balloon) NaN ,但是 parseFloat(123.45balloon) 123.45 (作为数字)。

That is, Number("123.45balloon") is NaN, but parseFloat("123.45balloon") is 123.45 (as a number).

正如Kling先生指出的那样,那些更好取决于你。

As Mr. Kling points out, which of those is "better" is up to you.

编辑—啊,你已经加回了 + x ~~ x 。正如我在评论中写的那样, + x 相当于使用 Number()构造函数,但我认为这是一个由于 + 运算符的语法灵活性,风险很小。也就是说,剪切和粘贴很容易引入错误。如果你知道你想要一个整数(一个32位整数), ~~ x 表格是好的。对于lat / long而言,这可能不是你想要的。

edit — ah, you've added back +x and ~~x. As I wrote in a comment, +x is equivalent to using the Number() constructor, but I think it's a little risky because of the syntactic flexibility of the + operator. That is, it'd be easy for a cut-and-paste to introduce an error. The ~~x form is good if you know you want an integer (a 32-bit integer) anyway. For lat/long that's probably not what you want however.