在 Javascript 中选择数组时遇到问题
Having Trouble Selecting array in Javascript
Javascript 的新手。尝试从项目的天气 API 中提取数据,但 运行 成为一个我确信很容易解决的问题。这是我已经获取的数据:
{coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 9656, …}
coord: {lon: -76.13, lat: 43.04}
weather: Array(1)
0: {id: 500, main: "Rain", description: "light rain", icon: "10d"}
length: 1
__proto__: Array(0)
base: "stations"
main: {temp: 281.12, feels_like: 274.24, temp_min: 280.37, temp_max: 282.04, pressure: 1004, …}
visibility: 9656
wind: {speed: 8.2, deg: 310}
rain: {1h: 0.25}
clouds: {all: 90}
dt: 1587324361
sys: {type: 1, id: 5965, country: "US", sunrise: 1587291309, sunset: 1587340289}
timezone: -14400
id: 0
name: "Syracuse"
cod: 200
__proto__: Object
我需要做的是select"Rain"天气class。但是,由于它在数组内部,我不知道如何获取它。例如,如果我这样做
data.visibility
我当然会返回 9656。但是如果我这样做
data.weather.0
甚至 data.weather.["0"]
我会遇到以下错误:Uncaught SyntaxError: Unexpected number。即使我没有收到此错误,我将如何访问数组中的特定元素 "Rain"?
很抱歉,如果这是一个简单的修复,只是由于每次搜索时的措辞都非常具体,所以很难找到答案。
您可以这样访问:
data.weather[0].main
其中 0 是描述数组元素索引的整数。
如果只需要数组的第一个元素,可以简单地使用索引来获取值data.weather[0].main
。
或者您可以通过 Array 方法 data.weather.map(item => item.main)
映射一个数组。您将获得一个自定义数组 ["Rain"]
Javascript 的新手。尝试从项目的天气 API 中提取数据,但 运行 成为一个我确信很容易解决的问题。这是我已经获取的数据:
{coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 9656, …}
coord: {lon: -76.13, lat: 43.04}
weather: Array(1)
0: {id: 500, main: "Rain", description: "light rain", icon: "10d"}
length: 1
__proto__: Array(0)
base: "stations"
main: {temp: 281.12, feels_like: 274.24, temp_min: 280.37, temp_max: 282.04, pressure: 1004, …}
visibility: 9656
wind: {speed: 8.2, deg: 310}
rain: {1h: 0.25}
clouds: {all: 90}
dt: 1587324361
sys: {type: 1, id: 5965, country: "US", sunrise: 1587291309, sunset: 1587340289}
timezone: -14400
id: 0
name: "Syracuse"
cod: 200
__proto__: Object
我需要做的是select"Rain"天气class。但是,由于它在数组内部,我不知道如何获取它。例如,如果我这样做
data.visibility
我当然会返回 9656。但是如果我这样做
data.weather.0
甚至 data.weather.["0"]
我会遇到以下错误:Uncaught SyntaxError: Unexpected number。即使我没有收到此错误,我将如何访问数组中的特定元素 "Rain"?
很抱歉,如果这是一个简单的修复,只是由于每次搜索时的措辞都非常具体,所以很难找到答案。
您可以这样访问:
data.weather[0].main
其中 0 是描述数组元素索引的整数。
如果只需要数组的第一个元素,可以简单地使用索引来获取值data.weather[0].main
。
或者您可以通过 Array 方法 data.weather.map(item => item.main)
映射一个数组。您将获得一个自定义数组 ["Rain"]