【问题标题】:Pass fetch api results to function and use the processed data from the function将 fetch api 结果传递给函数并使用函数中处理过的数据
【发布时间】:2021-10-26 20:22:11
【问题描述】:

我正在从这个 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 jquery json fetch fetch-api


    【解决方案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>

    【讨论】:

      猜你喜欢
      • 2021-12-27
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-21
      • 2015-08-16
      • 1970-01-01
      相关资源
      最近更新 更多