Javascript vs Python with respect to Python 'map()' function

纵然是瞬间 提交于 2019-12-22 07:04:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!