数组map,filter,forEach的区别

今天自己练手的时候,分析了下这三个方法的用法。
一. map
它是由原数组每一项调用一个函数之后,返回一个新的数组 。

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

二.filter
它是由原数组每一项调用一个过滤函数,由过滤函数返回的true或者false来决定该项是否可以到一个新的数组里面,同样它也是返回一个新的数组。

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

三. forEach
它是由原数组每一项调用一个函数,但是在它里面不能用return,continue,break,具体可以看我之前写的for …of…那章

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

发布了11 篇原创文章 · 获赞 3 · 访问量 8777

猜你喜欢

转载自blog.csdn.net/weixin_44233892/article/details/104720117