js遍历方法

190 阅读4分钟

image.png

数组的遍历方式

foreach语句

array.foreach(function(currentValue,index,arr),thisValue)
foreach方法用于调用数组的每个元素,并将元素传递给回调函数。数组中的每个值都会调用回调函数。

    let arr = [1,2,3,4,5] 
    arr.forEach((item, index, arr) => { 
        console.log(index+":"+item) 
    })
  • forEach 方法不会改变原数组,也没有返回值;
  • forEach无法使用 break,continue 跳出循环,使用 return 时,效果和在 for 循环中使用 continue 一致;return只会跳出本次循环
  • forEach 方法无法遍历对象,仅适用于数组的遍历。
  • foreach 方法没有返回值,undefined

map()

map(function(currentValue,index,arr),thisValue) map()方法会返回一个新数组,数组中的元素为原数组的调用函数处理后的值。该方法按照原始数组的元素顺序依次处理元素。

let arr = [1, 2, 3]; 
arr.map(item => { return item + 1; }) 
// 输出结果: [2, 3, 4]
  • map 方法不会对空数组进行检测;
  • map 方法遍历数组时会返回一个新数组,不会改变原始数组
  • map 方法有返回值,可以return出来,map的回调函数中支持return返回值;
  • map 方法无法遍历对象,仅适用于数组的遍历。

for of

for(variable of iterable){ satatement }

  • variable:每个迭代的属性值被分配给该变量。
  • iterable:一个具有可枚举属性并且可以迭代的对象。
let arr = [ {id:1, value:'hello'}, {id:2, value:'world'}, {id:3, value:'JavaScript'} ] 
for (let item of arr) {
    console.log(item); } 
// 输出结果:{id:1, value:'hello'} {id:2, value:'world'} {id:3, value:'JavaScript'}
  • for of 方法只会遍历当前对象的属性,不会遍历其原型链上的属性;
  • for of 方法适用遍历 数组/ 类数组/字符串/map/set 等拥有迭代器对象的集合;
  • for of 方法不支持遍历普通对象,因为其没有迭代器对象。如果想要遍历一个对象的属性,可以用 for in 方法;
  • 可以使用break、continue、return来中断循环遍历;

filter()

array.filter(function(currentValue,index,arr),thisValue) filter()方法用于过滤数组,满足条件的元素被返回。它的参数是一个回调函数,所有元素依次执行该函数。返回结果为true的元素被返回,如果没有返回条件的元素,则返回空数组。

const arr = [1, 2, 3, 4, 5] 
arr.filter(item => item > 2) // 输出结果:[3, 4, 5]

可以使用filter()方法来移除数组中的undefined、null、NAN等值:

let arr = [1, undefined, 2, null, 3, false, '', 4, 0] 
arr.filter(Boolean) // 输出结果:[1, 2, 3, 4]
  • filter 方法会返回一个新的数组,不会改变原数组;
  • filter 方法不会对空数组进行检测;
  • filter 方法仅适用于检测数组。

some(),every()

array.some(function(currentValue,index,arr),thisValue) array.every(function(currentValue,index,arr),thisValue)

some()方法会对数组中的每一项进行遍历,只有有一个元素符合条件就返回true,且剩下的元素不会再检测

every()方法对数组中的每一项进行遍历,只有所有元素符合条件才返回true;如果数组中检测到有一个元素不符合,则整个表达式返回false,且剩下的元素不会再检测。

let arr = [1, 2, 3, 4, 5]
arr.some(item => item > 4) 

// 输出结果: true

let arr = [1, 2, 3, 4, 5]
arr.every(item => item > 0) 

// 输出结果: true
  • 两个方法都不会改变原数组,会返回一个布尔值;
  • 两个方法都不会对空数组进行检测;
  • 两个方法都仅适用于检测数组。

find()

array.find(function(currentValue,index,arr),thisValue) find()方法会通过函数内判断数组的第一个元素的值。当数组的元素在测试返回true时,find返回符合条件的元素,之后的值不会再调用执行函数。如果没有符合条件的元素就返回undefined

let arr = [1, 2, 3, 4, 5]
arr.find(item => item > 2) 

// 输出结果: 3

let arr = [1, 2, 3, 4, 5]
arr.findIndex(item => item > 2) 

// 输出结果: 2
  • find():返回的是第一个符合条件的值;
  • findIndex:返回的是第一个返回条件的值的索引值。
  • 两个方法对于空数组,函数是不会执行的;
  • 两个方法否不会改变原数组。

对象遍历的方法

for in

for(var i in obj){ 执行的代码块 }

var obj = {a: 1, b: 2, c: 3}; 
 
for (var i in obj) { 
    console.log('键名:', i); 
    console.log('键值:', obj[i]); 
}
//键名: a 键值: 1 键名: b 键值: 2 键名: c 键值: 3
  • for in 方法不仅会遍历当前的对象所有的可枚举属性,还会遍历其原型链上的属性。