我在尝试从 CMC 获取 ETH 最后价格时得到 "undefined"

I'm getting "undefined" when trying to get ETH last price from CMC

我有一个小的价格小部件,它可以显示 CMC 上以太坊的最新价格

<script>
  $.ajax({

    url : 'https://api.coinmarketcap.com/v1/ticker/ethereum/',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {
        console.log(data);
    },
    error : function(request,error)
    {
        console.log('Error by getting the ETH price');
    }
  });
  </script>

url 包含所有这些数据

[
{
"id": "ethereum",
"name": "Ethereum",
"symbol": "ETH",
"rank": "2",
"price_usd": "138.566166052",
"price_btc": "0.01850224",
"24h_volume_usd": "7342353696.2",
"market_cap_usd": "15125162393.0",
"available_supply": "109154802.0",
"total_supply": "109154802.0",
"max_supply": null,
"percent_change_1h": "-0.34",
"percent_change_24h": "2.83",
"percent_change_7d": "3.31",
"last_updated": "1578254485"
}
]

当我为 price_usd:

执行操作时,我的 console.log 输出显示未定义
console.log(data[4]); 

如何访问 price_usd?

对于 data 变量,您有一个数组,其中包含一个具有其属性的对象。要访问该对象,您可以使用 data[0] 这是数组的第一个元素。然后像data[0].propertyName.

这样的属性

如果数组中只有 1 个元素,您可以这样做:data[0].price_usd。但值得检查它是否具有值,例如:data && data.length > 0 ? data[0].price_usd : undefined.

喜欢以下内容:

const data = [{
    "id": "ethereum",
    "name": "Ethereum",
    "symbol": "ETH",
    "rank": "2",
    "price_usd": "138.566166052",
    "price_btc": "0.01850224",
    "24h_volume_usd": "7342353696.2",
    "market_cap_usd": "15125162393.0",
    "available_supply": "109154802.0",
    "total_supply": "109154802.0",
    "max_supply": null,
    "percent_change_1h": "-0.34",
    "percent_change_24h": "2.83",
    "percent_change_7d": "3.31",
    "last_updated": "1578254485"
}];

const result = data && data.length > 0 ? data[0].price_usd : undefined;
console.log(result);

您可以使用 data[] 数组元素访问,在这种情况下不能使用属性:

const data = ['first', 'second', 'third', 'fourth', 'fifth'];
console.log(data[4]);

或者更好的例子,只需考虑以下内容:

const data = [{price_usd: 123}];
const firstElementOfArray = data[0];

console.log({firstElementOfArray});
console.log('price_usd', firstElementOfArray.price_usd);

我建议阅读以更好地理解:

  1. https://www.w3schools.com/js/js_arrays.asp
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

希望对您有所帮助!