返回

巧用遍历和定位法,捕捉信息之弦

前端

## 数组

1. for-of 循环

// 遍历数组,并输出每个元素
const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
  console.log(number);
}
// 输出:1 2 3 4 5

2. forEach() 方法

// 遍历数组,并输出每个元素
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
  console.log(number);
});
// 输出:1 2 3 4 5

3. map() 方法

// 遍历数组,并将每个元素增加1,然后输出结果
const numbers = [1, 2, 3, 4, 5];
const result = numbers.map((number) => number + 1);
console.log(result);
// 输出:[2, 3, 4, 5, 6]

4. filter() 方法

// 遍历数组,并输出大于3的元素
const numbers = [1, 2, 3, 4, 5];
const result = numbers.filter((number) => number > 3);
console.log(result);
// 输出:[4, 5]

5. find() 方法

// 遍历数组,并输出第一个大于3的元素
const numbers = [1, 2, 3, 4, 5];
const result = numbers.find((number) => number > 3);
console.log(result);
// 输出:4

6. findIndex() 方法

// 遍历数组,并输出第一个大于3的元素的索引
const numbers = [1, 2, 3, 4, 5];
const result = numbers.findIndex((number) => number > 3);
console.log(result);
// 输出:3

7. includes() 方法

// 检查数组是否包含某个元素
const numbers = [1, 2, 3, 4, 5];
const result = numbers.includes(3);
console.log(result);
// 输出:true

8. indexOf() 方法

// 返回数组中某个元素的索引,如果没有找到返回-1
const numbers = [1, 2, 3, 4, 5];
const result = numbers.indexOf(3);
console.log(result);
// 输出:2

9. lastIndexOf() 方法

// 返回数组中某个元素的最后一个索引,如果没有找到返回-1
const numbers = [1, 2, 3, 4, 5, 3];
const result = numbers.lastIndexOf(3);
console.log(result);
// 输出:5

## 对象

1. for-in 循环

// 遍历对象,并输出每个属性的值
const person = {
  name: 'John',
  age: 30,
  city: 'New York',
};
for (const property in person) {
  console.log(person[property]);
}
// 输出:John 30 New York

2. Object.keys() 方法

// 将对象的属性名放入数组,并输出
const person = {
  name: 'John',
  age: 30,
  city: 'New York',
};
const keys = Object.keys(person);
console.log(keys);
// 输出:['name', 'age', 'city']

3. Object.values() 方法

// 将对象的值放入数组,并输出
const person = {
  name: 'John',
  age: 30,
  city: 'New York',
};
const values = Object.values(person);
console.log(values);
// 输出:['John', 30, 'New York']

4. Object.entries() 方法

// 将对象的属性名和值放入二维数组,并输出
const person = {
  name: 'John',
  age: 30,
  city: 'New York',
};
const entries = Object.entries(person);
console.log(entries);
// 输出:[ [ 'name', 'John' ], [ 'age', 30 ], [ 'city', 'New York' ] ]

5. forEach() 方法

// 遍历对象,并输出每个属性的值
const person = {
  name: 'John',
  age: 30,
  city: 'New York',
};
Object.keys(person).forEach((property) => {
  console.log(person[property]);
});
// 输出:John 30 New York

## 总结

本文介绍了各种遍历和定位方法,包括数组和对象。这些方法可以帮助您轻松访问和处理数据,使编程更加高效。希望您能熟练掌握这些方法,并在您的项目中灵活运用。