2017-07-18 49 views
0

我通過jQuery的get函數獲取JSON數據:刪除前導號碼(jQuery的獲取)

$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) { 
    $.each(data, function (index, item) { 
     var ticker = { 
      id: [item.id], 
      name: [item.name], 
      symbol: [item.symbol], 
      rank: [item.rank], 
      price_usd: [item.price_usd], 
      price_btc: [item.price_btc], 
      24h_volume_usd: [item.24h_volume_usd], 
      market_cap_usd: [item.market_cap_usd], 
      available_supply: [item.available_supply], 
      percent_change_1h: [item.percent_change_1h], 
      percent_change_24h: [item.percent_change_24h], 
      percent_change_7d: [item.percent_change_7d], 
      last_updated: [item.last_updated] 
     }; 
    }); 
}); 

作爲一個例子,該項目變量本身(的console.log)包含此類型的數據:

{ 
    id: "bitcoin", 
    name: "Bitcoin", 
    symbol: "BTC", 
    rank: "1", 
    price_usd: "2238.86", 
    price_btc: "1.0", 
    24h_volume_usd: "1206490000.0" 
    // ... 
} 

然而,當我嘗試訪問item.24h_volume_usd,javascript的拋出以下錯誤:

SyntaxError: identifier starts immediately after numeric literal

我後來看到JavaScript不能有以數字開頭的變量。所以問題是:

那麼我如何訪問這個變量呢?

+0

這不是一個變量。變量名稱不能以數字字符開頭。 –

回答

2

使用括號符號即item["24h_volume_usd"]閱讀並同時確定財產(屬性名以數字開頭)包裝在引號

var data = { 
 
    "24h_volume_usd": "1206490000.0" 
 
} 
 

 
console.log(data["24h_volume_usd"])

不過,我會建議你使用有效身份標識。

+2

恭喜100k! –

+0

這是完全有效的,如果你不介意這樣做。 –