Javascript 将 json 对象值视为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6174105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
treat json objects value as integer
提问by KooiInc
I have a json file which I am accessing through JS
我有一个通过 JS 访问的 json 文件
latitude =data8.weblandmarks8[j].latitude + latitude;
should add all the latitudes so that I could average them later instead it just concatenates them How should i achieve what I want to
应该添加所有纬度,以便我以后可以平均它们,而不是将它们连接起来我应该如何实现我想要的
Json entry
JSON 条目
"latitude": "28.14331",
回答by KooiInc
Aside from using parseFloat
you could convert to Number
, it's slightly faster and usable for both integers and floats1:
除了使用parseFloat
你可以转换为Number
,它稍微快一点,可用于整数和浮点数1:
latitude = Number(data8.weblandmarks8[j].latitude) + latitude;
1another advantage for integers is that you don't need to supply a radix. Number('09')
returns 9, whereas parseInt('09')
(i.e. parseInt
without a radix) returns 0 (that's because parseInt
defaults to an octal - radix 8).
1整数的另一个优点是您不需要提供基数。 Number('09')
返回 9,而parseInt('09')
(即parseInt
没有基数)返回 0(这是因为parseInt
默认为八进制 - 基数 8)。
回答by peterp
Convert it to a number: You'll use the parseFloat()
or parseInt()
methods.
将其转换为数字:您将使用parseFloat()
orparseInt()
方法。
parseFloat('28.14331') // 28.14331
parseInt('28.14331', 10) // 28
回答by Ibu
you can use the parseFloat function to turn the string into a number
您可以使用 parseFloat 函数将字符串转换为数字
latitude = parseFloat(data8.weblandmarks8[j].latitude) + latitude;