js数组的迭代方法every、filter、forEach、map、some

mac2024-03-30  33

1.迭代方法 ES5为数组定义了5个迭代方法,这五个迭代函数分别是:every()、filter()、forEach()、map()、some()。每个方法都接收两个参数:在数组里面的每一项上运行的函数和(可选)运行该函数的作用域对象——影响this的指向。传入这些方法中的函数会接收三个参数:数组每一项的值(必需)、该项在数组中的位置(可选)、数组对象本身(可选)。

/** 我们这边使用forEach举例分别输出一下看看这个五个方法的参数如何使用以及数组每项运行函数的三个参数分别打印出来 **/ var color = ['red', 'yellow', 'green', 'blue', 'black']; var colorObj = {name: 'lilei'} color.forEach(function(item, index, arr) { //console.log(item) //console.log(index) //console.log(arr) //上面说了迭代方法的第二个参数会影响this的指向,我把第二参数写为新创建的colorObj对象。接下来打印this,看看this输出的是什么 console.log(this) }, colorObj)

首先打印this看看输出的是什么。 因为forEach()方法相当于for循环且数组的长度是5,所以打印了5次this。可以看到,因为forEach()方法的第二参数传入的是创建好的 person 对象。输出出来的this就是指向了person这个对象。

接下来把该方法的每个项的运行函数的三个参数(item, index, arr)分别打印出来看看。

var color = ['red', 'yellow', 'green', 'blue', 'black']; var colorObj = {name: 'lilei'} //为了方便打印,把index作为对象colorObj的属性,item作为属性的值。 color.forEach((item, index, arr) => { console.log(index+ '数组的index ' + item + '数组的item'); console.log(arr); }, colorObj)

可以看出,item就是数组个每一项,index就是item在数组当中的下标,arr就是指当前数组。

接下来看看五个迭代函数的用法 (1)every()返回值是布尔值。对数组中的每一项给运行函数去执行,如果该函数的每一项都返回true,则返回true。

var num = [2, 3, 4, 5, 6]; num.every(function(item) { return item > 1 }) // 因为数组里面的每一项都大于1,所以返回true num.every(function(item) { return item > 2 }) //因为数组里面下标为 0 的2 不满足大于2的条件,所以返回false

(2)filter()返回值是满足函数内部条件的项组成的数组。

var num = [1, 2, 3, 4, 5, 6]; var res = num.filter(function(item) { return item > 2 }) console.log(res)//[3, 4, 5, 6]

(3)forEach()对数组的每一项给定运行函数,这个方法没有返回值。

var num = [1, 2, 3, 4, 5, 6]; var arr = []; num.forEach(function(item) { arr.push(item + 5) }) console.log(arr)// [6, 7, 8, 9, 10, 11];

(4)map()对数组中的每一项给定运行函数,返回每次函数调用的运行结果组长的数组

var color = ['red', 'blue', 'yellow', 'green']; var res = color.map(function(item) { return '我是' + item; }) console.log(res);// ["我是red", "我是blue", "我是yellow", "我是green"]

(5)some()返回值是布尔值,对数组中的每一项给定运行函数,如果函数对任一项返回true则该方法返回true。

var num = [23, 41, 61, 11, 45, 9]; var res = num.some(function(item) { return item % 2 == 0; }) console.log(res); // false 因为num数组里面的每一项都不能整除2,所以会返回false //同样的例子,只需要把num数组当中的任意一项改成能被2整除的数,结果就会返回true var num = [23, 41, 61, 10, 45, 9]; var res = num.some(function(item) { return item % 2 == 0; }) console.log(res); //true
最新回复(0)