我的my(javascript)API出现问题。当我使用coinmarketcap API(https://api.coinmarketcap.com/v1/ticker)时。对于比特币的“max_supply”,它在文本中给出了“16865112.0”。这是个问题。我想自动把逗号放在像16,865,112.0这样的数字中。
如果数据id是例如以太坊(它没有最大供应量),它会给我∞。这很有效。
原件:
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
for (var i = 0; i < data.length - 1; i++) {
if (data[i].id == "bitcoin") {
$("#max_supply").html(data[i].max_supply == null ? '∞' : data[i].max_supply);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="max_supply"></div>
这给了我一个输出“21000000.0”
这是我到目前为止所得到的
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
for (var i = 0; i < data.length - 1; i++) {
if (data[i].id == "bitcoin") {
$("#max_supply").html(Number(data[i].max_supply).toLocaleString('en-US') == null ? '∞' : data[i].max_supply.toLocaleString('en-US'));
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="max_supply"></div>
这不会给我输出。
有什么建议吗?
答案 0 :(得分:1)
首先,您应该在for循环中取消-1
,否则您将丢失最后一项。
下面的三元maxSupply = maxSupply == null ? '∞' : numberWithCommas(maxSupply)
表示如果最大供应值为空(对于JSON中的当前硬币),则将maxSupply设置为∞
,否则将maxSupply var设置为numberWithCommas(maxSupply)
我从https://stackoverflow.com/a/2901298/1309377获得了numberWithCommas(...)
功能,以帮助您按照要求使用逗号格式化数字。
我也改为.append()
而不是.html()
,否则你只会自己写一遍。
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
for (var i = 0; i < data.length; i++) {
var coin = data[i].id;
var maxSupply = data[i].max_supply;
maxSupply = maxSupply == null ? '∞' : numberWithCommas(maxSupply)
$("#max_supply").append(coin + ": " + maxSupply + "<br/>");
}
});
function numberWithCommas(x){
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Max Supply</span>
<div id="max_supply"></div>
&#13;