The difference between an array of map, filter, forEach the

When his practiced hand today, we are analyzing the usage under these three methods.
A. Map
it is the original array after each call to a function that returns a new array.

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]

Two .filter
it is the original array each call a filter function that returns the filter function of true or false to determine whether the item can go to a new array inside, it is also the same returns a new array.

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"]

Three. ForEach
it is the original array a call to each function,? But inside it can not return, continue, break, concrete can see before I wrote that chapter for ... of ...

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

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

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

Published 11 original articles · won praise 3 · Views 8777

Guess you like

Origin blog.csdn.net/weixin_44233892/article/details/104720117
Recommended