将 fetch api 结果传递给函数并使用函数处理后的数据

问题描述 投票:0回答:1

我正在从此 api 获取数字

let fetchRes = fetch("https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX")
  .then((res) => res.json())
  .then((result) => {
    console.log(result);
    document.getElementById('result').innerHTML = result.data[0].market_cap;
  })
  .catch(error => {
    console.log(error);
  })

我希望获取的数字(例如 7692083188)以 7.69B 的形式显示。 我知道这个转换代码,但如何连接这两个代码才能使我的数据显示为 7.69B?

function convertToInternationalCurrencySystem (labelValue) {

    // Nine Zeroes for Billions
    return Math.abs(Number(labelValue)) >= 1.0e+9

    ? (Math.abs(Number(labelValue)) / 1.0e+9).toFixed(2) + "B"
    // Six Zeroes for Millions 
    : Math.abs(Number(labelValue)) >= 1.0e+6

    ? (Math.abs(Number(labelValue)) / 1.0e+6).toFixed(2) + "M"
    // Three Zeroes for Thousands
    : Math.abs(Number(labelValue)) >= 1.0e+3

    ? (Math.abs(Number(labelValue)) / 1.0e+3).toFixed(2) + "K"

    : Math.abs(Number(labelValue));

}

( convertToInternationalCurrencySystem (7692083188) );
   
javascript fetch-api
1个回答
1
投票

您只需通过更改此行将

#result
innerHTML 设置为
convertToInternationalCurrencySystem(result.data[0].market_cap)

document.getElementById('result').innerHTML = result.data[0].market_cap;

对此:

document.getElementById('result').innerHTML = convertToInternationalCurrencySystem(result.data[0].market_cap);

检查并运行以下代码片段以获取上述内容的实际示例:

function convertToInternationalCurrencySystem(labelValue) {

    // Nine Zeroes for Billions
    return Math.abs(Number(labelValue)) >= 1.0e+9

    ? (Math.abs(Number(labelValue)) / 1.0e+9).toFixed(2) + "B"
    // Six Zeroes for Millions 
    : Math.abs(Number(labelValue)) >= 1.0e+6

    ? (Math.abs(Number(labelValue)) / 1.0e+6).toFixed(2) + "M"
    // Three Zeroes for Thousands
    : Math.abs(Number(labelValue)) >= 1.0e+3

    ? (Math.abs(Number(labelValue)) / 1.0e+3).toFixed(2) + "K"

    : Math.abs(Number(labelValue));

}

let fetchRes = fetch("https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX")
  .then((res) => res.json())
  .then((result) => {
    document.getElementById('result').innerHTML = convertToInternationalCurrencySystem(result.data[0].market_cap);
  })
  .catch(error => {
    console.log(error);
  })
<h1 id="result"></h1>

© www.soinside.com 2019 - 2024. All rights reserved.