js中的遍历

1.for循环,需要数组的长度

我们定义一个数组

var arr = ['a','b',3,4];
for(var i=0;i<arr.length;i++){
  console.log(arr[i]); 
}

for in(常用语遍历对象)

//for in也可以遍历数组
for
(var i in arr){   console.log(arr[i]); }

使用for in 也可以遍历数组,但是会存在以下问题:

  1.index索引为字符串型数字,不能直接进行几何运算

  2.遍历顺序有可能不是按照实际数组的内部顺序

  3.使用for in会遍历数组所有的可枚举属性,包括原型

var arr = [{a:1,},{a:2},{a:3}]
    arr.name=112
    for(var i in arr){
        console.log(typeof i)
        console.log(arr[i]); 
    }

输出结果为:

所以for in更适合遍历对象。

for of则不会循环出上例中的name

var arr = [{a:1,},{a:2},{a:3}]
    arr.name=112
    for(var i of arr){
        console.log(i)
    }

 输出结果为:

for in遍历的是数组的索引(即键名),而for of遍历的是数组元素值。

2.forEach循环,不必知道数组长度,没有返回值。(es5)

1 arr.forEach(function(item,index,arr){
    //item为当前遍历的内容,index为索引,arr为数组本身
2 console.log(index,item,arr); 3 })

jquery中有$.each()方法,前两个参数正好相反

注:使用foreach遍历数组的话,使用break不能中断循环,使用return也不能返回到外层函数 

3. map函数,遍历数组每个元素,并回调操作,需要返回值,返回值组成新的数组,原数组不变(es6)

var arr = [1,2,3,4];
var
myMap = arr.map(function(item,index,arr){ return item*item; }) console.log(myMap) //逐个值求平方,输出新数组[1, 4, 9, 16]

4. filter函数, 过滤通过条件的元素组成一个新数组, 原数组不变(es6)

var arr = [1,2,'3','a'];
var
numArr = arr.filter(function(i){ return typeof i ==='number'; })
console.log(numArr) //输出新数组[1,2]

map和filter参数相同

var newArray = arr.map(function callback(currentValue, index, array){
//对每个元素的处理
})
参数
callback:用来生成新数组用的函数。
callback的参数:
currentValue:当然正在处理的元素
index:正在处理元素的索引
array:调用map方法的数组(就是.map()前面的也就是arr)

5. some函数,遍历数组中是否有符合条件的元素,返回Boolean值,只要有一个为真返回真(es5)

var arr = [1,2,'3','a'];
var
mySome = arr.some(function(i){ return typeof i ==='number'; })
console.log(mySome) //true

6. every函数, 遍历数组中是否每个元素都符合条件, 返回Boolean值,全部为真返回真(es5)

var arr = [1,2,'3','a'];
var
myEvery = arr.every(function(i){ return typeof i ==='number'; })
console.log(myEvery) //false

 7. reduce/reduceRight函数,对数据遍历并进行操作(es5)

var myarr = [1,3,5,7,9]
var initialValue = 10 //可选。传递给函数的初始值
var plus = myarr.reduce(function(total, num,index,arr){
        console.log('total:',total) //必需。初始值, 或者计算结束后的返回值。
        console.log('num:',num) //必需。当前元素
        console.log('index:',index) //可选。当前元素的索引
        console.log('arr:',arr)   //可选。当前元素所属的数组对象。
        return total + num;
    },10)
console.log('plus:',plus) //计算10+1+3+5+7+9

 输出结果:

reduceRight方法功能和reduce一样,不过是从右边开始遍历。

(个人总结,如有错误,欢迎指正)

猜你喜欢

转载自www.cnblogs.com/jidi/p/8885967.html