js从json数组中取值
时间: 2024-03-16 14:44:16 浏览: 65
浅谈json取值(对象和数组)
假设有一个如下的JSON数组:
```
[
{
"name": "John",
"age": 30,
"city": "New York"
},
{
"name": "Jane",
"age": 25,
"city": "Los Angeles"
},
{
"name": "Bob",
"age": 40,
"city": "Chicago"
}
]
```
如果要取第一个对象的`name`属性,可以使用以下代码:
```
var data = [
{
"name": "John",
"age": 30,
"city": "New York"
},
{
"name": "Jane",
"age": 25,
"city": "Los Angeles"
},
{
"name": "Bob",
"age": 40,
"city": "Chicago"
}
];
var name = data[0].name;
console.log(name); // 输出 "John"
```
如果要取第二个对象的`age`属性,可以使用以下代码:
```
var age = data[1].age;
console.log(age); // 输出 25
```
如果要遍历整个数组并输出每个对象的`name`属性,可以使用以下代码:
```
for (var i = 0; i < data.length; i++) {
console.log(data[i].name);
}
```
输出:
```
John
Jane
Bob
```
阅读全文