问题
In Python there is a function called map
that allows you to go: map(someFunction, [x,y,z])
and go on down that list applying the function. Is there a javascript equivalent to this function?
I am just learning Python now, and although I have been told javascript is functional language, I can see that I have been programming in a non-functional javascript style. As a general rule, can javascript be utilized as a functional language as effectively as Python can? Does it have similar tricks like the map
function above?
I've also just begun an SML course and am wondering how much of what I learn will be applicable to javascript as well.
回答1:
Sure! JavaScript doesn't have a lot of higher-order functions built-in, but map
is one of the few that is built-in:
var numbers = [1, 2, 3];
var incrementedNumbers = numbers.map(function(n) { return n + 1 });
console.log(incrementedNumbers); // => [2, 3, 4]
It might be worthwhile to note that map
hasn't been around forever, so some rather old browsers might not have it, but it's easy enough to implement a shim yourself.
回答2:
You can also use underscore.js which adds tons of nice functionalists with only 4k size.
_.map([1, 2, 3], function(num){ return num * 3; });
//=> [3, 6, 9]
来源:https://stackoverflow.com/questions/19851002/javascript-vs-python-with-respect-to-python-map-function