我通过jQuery的get函数获取JSON数据:
$.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:标识符在数字文字
之后立即开始
之后我读到javascript不能包含以数字开头的变量。所以问题是:
我如何访问此变量?
答案 0 :(得分:2)
使用括号表示法,即item["24h_volume_usd"]
来读取和定义属性时将其用引号括起来(属性名称以数字开头)
var data = {
"24h_volume_usd": "1206490000.0"
}
console.log(data["24h_volume_usd"])
但是,我建议您使用有效的标识符。