The map in JS:
Because the map()
method is defined in JavaScript Array
, we call Array
the map()
method, passing in our own function, and get a new Array
result:
function Pow (x) { return x * x;} var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];arr.map (POW); [1, 4, 9, 16, 25, 36, 49, 64, 81]
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];arr.map(String); // [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘]
Map in Python:
def f (x): ... return x * x ... >>> r = Map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9])>>> list (R) [1, 4, 9, 16, 25, 36, 49, 64, 81 ]
map()
The first parameter passed in is the f
function object itself. Since the result r
is one Iterator
, it is an Iterator
inert sequence, so the list()
function allows it to calculate the entire sequence and return a list.
list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘]
Filter in Python:
like map (), filter () also receives a function and a sequence. Unlike map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false. def is_odd (n): return n% 2 = = 1list (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15 ])# results: [1, 5, 9, []
Map in JS in map and python