数组遍历方法

1.for循环

使用临时变量,将长度缓存起来,避免重复获取数组长度,当数组较大时优化效果才会比较明显。

1
2
3
for(j = 0,len=arr.length; j < len; j++) {
    
}

2.foreach循环

遍历数组中的每一项,没有返回值,对原数组没有影响,不支持IE

1
2
3
4
5
6
//1 没有返回值
arr.forEach((item,index,array)=>{
    //执行代码
})
//参数:value数组中的当前项, index当前项的索引, array原始数组;
//数组中有几项,那么传递进去的匿名回调函数就需要执行几次;

3.map循环

有返回值,可以return出来

map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);

1
2
3
4
5
6
7
arr.map(function(value,index,array){
 
  //do something
 
  return XXX
 
})
1
2
3
4
5
6
var ary = [12,23,24,42,1]; 
var res = ary.map(function (item,index,ary ) { 
    return item*10; 
}) 
console.log(res);//-->[120,230,240,420,10];  原数组拷贝了一份,并进行了修改
console.log(ary);//-->[12,23,24,42,1];  原数组并未发生变化

 

4.forof遍历

可以正确响应break、continue和return语句

1
2
3
for (var value of myArray) {
console.log(value);
}

  

5.filter遍历

不会改变原始数组,返回新数组

1
2
3
4
5
var arr = [
  { id: 1, text: 'aa', done: true },
  { id: 2, text: 'bb', done: false }
]
console.log(arr.filter(item => item.done))

转为ES5

1
2
3
arr.filter(function (item) {
  return item.done;
});
1
2
3
var arr = [73,84,56, 22,100]
var newArr = arr.filter(item => item>80)   //得到新数组 [84, 100]
console.log(newArr,arr)

  

6.every遍历

every()是对数组中的每一项运行给定函数,如果该函数对每一项返回true,则返回true。

1
2
3
4
5
var arr = [ 1, 2, 3, 4, 5, 6 ]; 
console.log( arr.every( function( item, index, array ){ 
        return item > 3; 
    })); 
false

 

7.some遍历

some()是对数组中每一项运行指定函数,如果该函数对任一项返回true,则返回true。

1
2
3
4
5
6
var arr = [ 1, 2, 3, 4, 5, 6 ]; 
   
    console.log( arr.some( function( item, index, array ){ 
        return item > 3; 
    })); 
true

  

8.reduce

reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。

1
var total = [0,1,2,3,4].reduce((a, b)=>a + b); //10

reduce接受一个函数,函数有四个参数,分别是:上一次的值,当前值,当前值的索引,数组

1
2
3
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){
 return previousValue + currentValue;
});

reduce还有第二个参数,我们可以把这个参数作为第一次调用callback时的第一个参数,上面这个例子因为没有第二个参数,所以直接从数组的第二项开始,如果我们给了第二个参数为5,那么结果就是这样的:

1
2
3
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){
 return previousValue + currentValue;
},5);

 

第一次调用的previousValue的值就用传入的第二个参数代替,

9.reduceRight

reduceRight()方法的功能和reduce()功能是一样的,不同的是reduceRight()从数组的末尾向前将数组中的数组项做累加。

reduceRight()首次调用回调函数callbackfn时,prevValue 和 curValue 可以是两个值之一。如果调用 reduceRight() 时提供了 initialValue 参数,则 prevValue 等于 initialValuecurValue 等于数组中的最后一个值。如果没有提供 initialValue 参数,则 prevValue 等于数组最后一个值, curValue 等于数组中倒数第二个值。

1
2
3
4
5
var arr = [0,1,2,3,4];
 
arr.reduceRight(function (preValue,curValue,index,array) {
    return preValue + curValue;
}); // 10

回调将会被调用四次,每次调用的参数及返回值如下:

如果提供一个初始值initialValue5:

1
2
3
4
5
var arr = [0,1,2,3,4];
 
arr.reduceRight(function (preValue,curValue,index,array) {
    return preValue + curValue;
}, 5); // 15

回调将会被调用五次,每次调用的参数及返回的值如下:

同样的,可以对一个数组求和,也可以使用reduceRight()方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
var arr = [1,2,3,4,5,6];
 
console.time("ruduceRight");
Array.prototype.ruduceRightSum = function (){
    for (var i = 0; i < 10000; i++) {
        return  this.reduceRight (function (preValue, curValue) {
            return preValue + curValue;
        });
    }
}
arr.ruduceRightSum();
console.log('最终的值:' + arr.ruduceSum()); // 21
console.timeEnd("ruduceRight"); // 5.725ms

10.find

find()方法返回数组中符合测试函数条件的第一个元素。否则返回undefined

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var stu = [
    {
        name: '张三',
        gender: '男',
        age: 20
    },
    {
        name: '王小毛',
        gender: '男',
        age: 20
    },
    {
        name: '李四',
        gender: '男',
        age: 20
    }
]
1
2
3
4
5
6
7
function getStu(element){
   return element.name == '李四'
}
 
stu.find(getStu)
//返回结果为
//{name: "李四", gender: "男", age: 20}

ES6方法

1
stu.find((element) => (element.name == '李四'))

11.findIndex

对于数组中的每个元素,findIndex 方法都会调用一次回调函数(采用升序索引顺序),直到有元素返回 true。只要有一个元素返回 true,findIndex 立即返回该返回 true 的元素的索引值。如果数组中没有任何元素返回 true,则 findIndex 返回 -1。

findIndex 不会改变数组对象。

1
2
[1,2,3].findIndex(function(x) { x == 2; });
// Returns an index value of 1.
1
2
[1,2,3].findIndex(x => x == 4);
// Returns an index value of -1.

12.keys,values,entries

ES6 提供三个新的方法 —— entries(),keys()和values() —— 用于遍历数组。它们都返回一个遍历器对象,可以用for...of循环进行遍历,唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for (let index of ['a''b'].keys()) {
console.log(index);
}
// 0
// 1
for (let elem of ['a''b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
for (let [index, elem] of ['a''b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"

js数组遍历方法总结的更多相关文章

  1. 浅谈6种JS数组遍历方法的区别

    本篇文章给大家介绍一下6种JS数组遍历方法:for.foreach.for in.for of.. each. ().each的区别.有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助. ...

  2. JS数组遍历方法

    常用数组遍历方法: 1.原始for循环 var a = [1,2,3]; for(var i=0;i<a.length;i++){ console.log(a[i]); //结果依次为1,2,3 ...

  3. JS数组遍历方法集合

    就让我们在逆战中成长吧,加油武汉,加油自己 1.for循环 使用零时变量将长度存起来,当数组较大时优化效果才会比较明显. var ar1=[2,4,6,8] for(var i=0;i<ar1. ...

  4. 转→js数组遍历 千万不要使用for...in...

    看到一篇内容还不错,但是排版实在糟糕, 逼死强迫症患者啊,直接拉下去找原文连接,找到了,但是已经消失了···500错误... 第一次因为实在看不下去一篇博客的排版, 为了排版而转载... 转载地址:h ...

  5. js数组遍历和对象遍历

    针对js各种遍历作一个总结分析,从类型用处:分数组遍历和对象遍历:还有性能,优缺点等. JS数组遍历: 1,普通for循环,经常用的数组遍历 var arr = [1,2,0,3,9]; for ( ...

  6. ES6 数组遍历方法的实战用法总结(forEach,every,some,map,filter,reduce,reduceRight,indexOf,lastIndexOf)

    目录 forEach every some map filter reduce && reduceRight indexOf lastIndexOf 前言 ES6原生语法中提供了非常多 ...

  7. 数组遍历方法forEach 和 map 的区别

    数组遍历方法forEach 和 map 的区别:https://www.cnblogs.com/sticktong/p/7602783.html

  8. js几种数组遍历方法.

    第一种:普通的for循环 ; i < arr.length; i++) { } 这是最简单的一种遍历方法,也是使用的最多的一种,但是还能优化. 第二种:优化版for循环 ,len=arr.len ...

  9. 浅谈JS的数组遍历方法

    用过Underscore的朋友都知道,它对数组(集合)的遍历有着非常完善的API可以调用的,_.each()就是其中一个.下面就是一个简单的例子: var arr = [1, 2, 3, 4, 5]; ...

随机推荐

  1. Failed to install the hcmon driver

    在安装虚拟机的时候出现“Failed to install the hcmon driver”错误,是之前VM没有卸载干净,提供两个参考解决方法: 1:在C盘的驱动文件夹也就是“C:\Windows\ ...

  2. taotao商城遇到的问题

    1,在进行测试的时候,访问:http://localhost:8080/taotao-manager-web/ 可以出现首页 2,做了mybatis逆向工程之后,整合了spring,mybatis,测 ...

  3. Java中的异常处理与抛出

    一.异常处理 程序运行过程中出现的,导致程序无法继续运行的错误叫做异常. Java中有多种异常,所有异常的父类是Throwable,他主要有两个子类Error和Exception. Error一般是J ...

  4. jdk和cglib动态代理

    一.原理区别:java动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理. 而cglib动态代理是利用asm开源包,对代理对象类的class文件加 ...

  5. leetcode python 042收集雨水

    '''给定n个非负整数表示每个条的宽度为1的高程图,计算下雨后能够捕获多少水.例如,鉴于[0,1,0,2,1,0,1,3,2,1,2,1],返回6.这个题要先算出盛满水后的高程图,减去前者就是雨水.盛 ...

  6. js /Date(1550273700000)/ 格式转换

    self.FormatJsonDate = function (jsonStr) { var tmp = ""; if (jsonStr == null || jsonStr == ...

  7. JS中的一元操作符

    表达式 一元操作符 优先级 结合性 运算顺序 表达式是什么? 就是JS 中的一个短语,解释器遇到这个短语以后会把对它进行计算,得到一个结果参与运算,我们把这种要参与到运算中的各种各样的短语称为表达式. ...

  8. aqua data studio 连接db2

    打开datastudio 右键本地数据库服务器 →注册服务器打开以下界面: 1:选择版本号(我这里是window 9.7版本的db2) 2:名称 按照需要的写 3.登录名/密码 4.ip port 数 ...

  9. SLAM for dummies中文翻译

    1.简介 本文的主要目的是简单介绍移动机器人领域中广泛应用的技术SLAM(同步定位与地图绘制)的理论基础以及应用细节.虽然目前存在很多关于SLAM技术的方方面面的论文,但是对于一个新手来说,仍然需要花 ...

  10. AIX下core文件的分析

    笔者曾在AIX系统下使用C语言开发多个应用系统.众所周知,C语言编写程序时容易出现内存使用不当的BUG,例如内存越界.使用野指针.内存未初始化等等.在程序运行时,这些BUG很可能造成程序崩溃,但在测试 ...