jquery有两个map方法。
一个是http://api.jquery.com/jQuery.map/ 主要用来遍历操作数组和对象,
另一个是http://api.jquery.com/map/ 主要用于遍历jquery对象。
今天我学习的是jQuery.map()对数组的操作。
方法定义是
jQuery.map( array, callback(elementOfArray, indexInArray) )
看来和python的map方法差不多,只是参数顺序不同。
python里的map方法是这样定义的 map(function, iterable, ...),可以接收多个迭代对象。
所以我想把之前学习python map的示例用jquery重写下
示例一:
>>> def cube(x): return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
用jquery写就是:
var arr = [1,2,3,4,5,6,7,8,9,10 ];
arr = jQuery.map(arr, function(n, i){
return (n*n*n);
});
console.log(arr);
示例二:
>>> def cube(x) : return x + x
...
>>> map(cube , "abcde")
['aa', 'bb', 'cc', 'dd', 'ee']
用jquery实现是:
arr = [ "a", "b", "c", "d", "e" ];
arr = jQuery.map(arr, function(n, i){
return (n+n);
});
console.log(arr);
另外,jquery.map方法还可以实现类似python filter的功能
例三:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
用jquery.map实现就是:
arr=$.map( [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24], function (a) {
return (a%2!=0&&a%3!=0?a : null);
});
console.log(arr);