零. 通用遍历方法
0.1 for...in...
let obj = {0:"a", 1:"b", 2:"c"}; for (let key in obj) { console.log(obj[key]) }
0.2 for...of...
let obj = {0:"a", 1:"b", 2:"c"}; for (let value of obj) { console.log(value) }
一. JS遍历对象
1.1 Object.keys()遍历
let obj = {0:"a", 1:"b", 2:"c"}; Object.keys(obj).forEach((key) => { console.log(key, obj[key]); });
1.2 Object.values()遍历
let obj = {0:"a", 1:"b", 2:"c"}; Object.values(obj).forEach((value, key) => { console.log(key, value); });
1.3 Object.entries()遍历
let obj = {0:"a", 1:"b", 2:"c"}; Object.entries(obj).forEach((value, key) => { console.log(key, value); });
1.4 Object.getOwnPropertyNames()
let obj = {0:"a", 1:"b", 2:"c"};
Object.getOwnPropertyNames(obj);
二. JS遍历数组
2.1 forEach语句
let arr = [1, 2, 3] arr.forEach((item) => { console.log(item) })
2.2 map方法
map不会改变原数组,callback执行返回的值会形成一个新的数组。
let arr = [1, 2, 3] let newArr = arr.map((item) => { item * 2 })
2.3 filter方法
filter将返回值为true的元素创建一个新数组。
let arr = [1, 2, 3] let newArr = arr.filter((item) => { item > 2 })
2.4 every方法
every,全部满足则返回true
let arr = [1, 2, 3] let res = arr.every((item) => { item > 2 }) //false
2.5 some方法
some,只有有一项满足则返回true
let arr = [1, 2, 3] let res = arr.some((item) => { item > 2 }) //true