遍历数组和对象的方法
时间: 2023-12-03 18:47:04 浏览: 57
jquery遍历筛选数组的几种方法和遍历解析json对象
遍历数组可以使用以下方法:
1. for 循环:
```javascript
const arr = [1, 2, 3];
for(let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
2. forEach 方法:
```javascript
const arr = [1, 2, 3];
arr.forEach((item) => {
console.log(item);
});
```
3. map 方法:
```javascript
const arr = [1, 2, 3];
arr.map((item) => {
console.log(item);
});
```
遍历对象可以使用以下方法:
1. for-in 循环:
```javascript
const obj = {
name: 'John',
age: 30,
city: 'New York'
};
for(let key in obj) {
console.log(`${key}: ${obj[key]}`);
}
```
2. Object.keys 方法:
```javascript
const obj = {
name: 'John',
age: 30,
city: 'New York'
};
Object.keys(obj).forEach((key) => {
console.log(`${key}: ${obj[key]}`);
});
```
3. Object.values 方法:
```javascript
const obj = {
name: 'John',
age: 30,
city: 'New York'
};
Object.values(obj).forEach((value) => {
console.log(value);
});
```
阅读全文