数组
-
forEach(): 对数组的每个元素执行提供的函数,没有返回值。const numbers = [1, 2, 3, 4, 5]; numbers.forEach((num) => console.log(num)); -
map(): 创建一个新数组,其中包含原数组的每个元素按照指定的函数进行转换。const doubled = numbers.map((num) => num * 2); -
filter(): 创建一个新数组,其中包含原数组的满足指定条件的元素。const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter((num) => num % 2 === 0); -
reduce(): 将数组的元素合并为一个单一的值,通过指定的回调函数来累积值。const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); -
some(): 检查数组中是否至少有一个元素满足指定条件,返回布尔值。const numbers = [1, 2, 3, 4, 5]; const hasEvenNumber = numbers.some((num) => num % 2 === 0); -
every(): 检查数组中是否所有元素都满足指定条件,返回布尔值。const numbers = [2, 4, 6, 8, 10]; const allEvenNumbers = numbers.every((num) => num % 2 === 0); -
find(): 返回数组中第一个满足指定条件的元素,如果找不到则返回undefined。const numbers = [1, 2, 3, 4, 5]; const found = numbers.find((num) => num > 2); -
indexOf()和lastIndexOf(): 返回指定元素在数组中的索引位置,如果找不到则返回-1。const numbers = [1, 2, 3, 4, 3]; const indexOf3 = numbers.indexOf(3); // 返回 2 const lastIndexOf3 = numbers.lastIndexOf(3); // 返回 4 -
for...of循环: 使用for...of循环遍历数组中的元素。const numbers = [1, 2, 3, 4, 5]; for (const num of numbers) { console.log(num); }
对象
-
for...in循环:for...in循环用于遍历对象的可枚举属性名称。它会遍历对象自身的属性以及从原型链继承的属性。const person = { name: 'Alice', age: 30 }; for (const key in person) { console.log(key, person[key]); } -
Object.keys(obj): 返回一个数组,包含对象obj的所有可枚举属性的名称。const person = { name: 'Alice', age: 30 }; const keys = Object.keys(person); // 返回 ['name', 'age'] -
Object.values(obj): 返回一个数组,包含对象obj的所有可枚举属性的值。const person = { name: 'Alice', age: 30 }; const values = Object.values(person); // 返回 ['Alice', 30] -
Object.entries(obj): 返回一个包含对象obj所有可枚举属性的键-值对数组。const person = { name: 'Alice', age: 30 }; const entries = Object.entries(person); // 返回 [['name', 'Alice'], ['age', 30]] -
Object.getOwnPropertyNames(obj): 返回一个数组,包含对象obj的所有属性名称,包括不可枚举属性。const person = { name: 'Alice', age: 30 }; const propertyNames = Object.getOwnPropertyNames(person); // 返回 ['name', 'age'] -
for...of循环(ES6):for...of循环用于遍历可迭代对象,但在普通对象上通常不用于遍历属性。const iterable = [1, 2, 3]; for (const value of iterable) { console.log(value); }
总结:对象遍历方法的选择取决于你要遍历的对象以及你关心的属性。for...in 循环常用于遍历对象属性,而 Object.keys()、Object.values() 和 Object.entries() 用于获取对象的属性名称、属性值以及键-值对数组