本文介绍了访问以number开头的javascript对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用一个返回对象的api

I am calling an api which returns an object

var rain = data[i].rain;

$.get( "http://api.openweathermap.org/data/2.5/forecast?q=London,uk&mode=json&units=metric", function( data ) {
    var data = data.list;
    for(var i = 0; i < 12; i++){
        var rain = data[i].rain;
        console.log(rain)
    }
});

当我检查控制台时,雨返回以下内容:

rain returns the following when I inspect the console:

Object {3h: 0.005}
Object {3h: 0.03}

我预计 rain.3h 会让我访问0.005和0.03,但事实并非如此。我收到以下错误消息:意外的令牌ILLEGAL

I expected that rain.3h would have given me access to 0.005 and 0.03, but it doesn't. I get the following error message : Unexpected token ILLEGAL

这是因为它以数字开头吗?任何人都可以建议如何访问这个属性?

Is this because it begins with a number? Can anyone advise how to access this property?

推荐答案

是的,因为它以数字开头。

Yes it's because it begins with a number.

你可以这样访问:

rain['3h']

如果您有以数字或符号命名的对象属性,请使用括号表示法。

When you have object properties named with numbers or simbols, use the bracket notation.

这篇关于访问以number开头的javascript对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:20