Home  >  Article  >  Web Front-end  >  javascript functional programming programmer's toolset_javascript skills

javascript functional programming programmer's toolset_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:37:061079browse

If you look carefully at the sample code that has appeared so far, you will find that some of the methods here are not familiar. They are the map(), filter(), and reduce() functions, which are crucial to functional programming in any language. They allow you to write cleaner code without using loops and statements.

The map(), filter() and reduce() functions form the core part of the functional programmer's toolset. This toolset includes a series of pure, high-order functions that are the mainstay of the functional approach. In fact, they are typical of pure functions and higher-order functions. They take a function as input, return an output result, and produce no side effects.

However, they are ECMAScript 5.1 implementation standards in browsers, and they only work with arrays. Each time they are called, a new array will be created and returned, while the existing array will not be changed. They take functions as input, often using anonymous functions as callback functions. They iterate through the array and apply the function to each element of the array!

myArray = [1,2,3,4];
newArray = myArray.map(function(x) {return x*2});
console.log(myArray); // Output: [1,2,3,4]
console.log(newArray); // Output: [2,4,6,8]

Another point is that they only work on arrays and cannot work on other iterable data structures, such as objects. Don't worry, there are many libraries such as Underscore.js, Lazy.js, stream.js, etc. that implement their own more powerful map(), filter() and reduce().

Callback

If you have never used callbacks before, the concept may be a bit confusing. Especially in Javascript, Javascript provides several ways to declare functions.

Callback functions are used to pass to another function for their use. This is a way to pass logic like passing objects:

var myArray = [1,2,3];
function myCallback(x){return x+1};
console.log(myArray.map(myCallback));



For simpler tasks you can use anonymous functions:

console.log(myArray.map(function(x){return x+1}));

Callbacks are not only used in functional programming, they can do many things in Javascript. Just as an example, here's the callback() function for jQuery's AJAX calls:

function myCallback(xhr) {
 console.log(xhr.status);
 return true;
}
$.ajax(myURI).done(myCallback);

Note that only the name of the function is used here, because we are not calling the function but passing the function. It would be wrong to write it like this:

$.ajax(myURI).fail(myCallback(xhr)); 
// 或者
$.ajax(myURI).fail(myCallback());

What happens if we call the function? In this example, myCallback(xhr) will try to execute, the console will print "undefined", and will return true. When ajax() completes the call, the callback function it found based on its name will be "true" and an error will be reported.

That is to say, we cannot specify what parameters to pass to the callback function. If our callback function needs the ajax() function to pass it the parameters we want, we can wrap the return function in an anonymous function:

function myCallback(status) {
 console.log(status);
 return true;
}
$.ajax(myURI).done(function(xhr) {
 myCallback(xhr.status)
});

Array.prototype.map()

map() is the leader of these functions. It simply applies a callback function to the elements in the array.

Syntax: arr.map(callback [, thisArg]);

Parameters:
•callback(): This function generates an element for the new array. The parameters it receives: ◦currentValue: the element currently traversed in the array
◦index: the current element number in the array
◦array: the array currently being processed

•thisArg: This is an optional parameter. When the callback is executed, it serves as this

of the callback function.

Example:

var
 integers = [1, -0, 9, -8, 3],
 numbers = [1, 2, 3, 4],
 str = 'hello world how ya doing?';
 
// 将整数映射为他们自己的绝对值
console.log(integers.map(Math.abs));

// 将数组中的元素与自己的位置序数相乘
console.log(numbers.map(function(x, i) {
 return x * i
}));
// 单词隔一个变一个大写
console.log(str.split(' ').map(function(s, i) {
 if (i % 2 == 0)
  return s.toUpperCase();
 else
  return s;
}));



Although the Array.prototype.map method is the standard method for array objects in Javascript, you can easily extend your own objects.

MyObject.prototype.map = function(f) {
  return new MyObject(f(this.value));
 }; 

Array.prototype.filter()

The filter() function is used to filter out some elements in the array. The callback function must return true (keep it in the new array) or false (throw it away). You can use map() to do something similar, which is to return null as null for the elements you want to throw away. However, the filter() function will delete these unnecessary elements in the new array instead of leaving null to occupy the position.

Syntax: arr.filter(callback [, thisArg]);

•callback(): This function is used to test each element in the array. It should return true, otherwise it returns false. It has these parameters: ◦currentValue: the element currently traversed in the array
◦index: the ordinal number of the current element in the array
◦array: the array currently being processed

•thisArg: This is an optional parameter. When the callback is executed, it serves as this

of the callback function.

Example:

var myarray = [1, 2, 3, 4]
words = 'hello 123 world how 345 ya doing'.split(' ');
re = '[a-zA-Z]';
// 筛选整数
console.log([-2, -1, 0, 1, 2].filter(function(x) {
 return x > 0
}));
// 筛选所有含字母的单词
console.log(words.filter(function(s) {
 return s.match(re);
}));
// 随机移除数组中的元素
console.log(myarray.filter(function() {
 return Math.floor(Math.random() * 2)
}));

Array.prototype.reduce()

reduce()函数,有时也称为fold,它用于把数组中的所有值聚集到一起。回调需要返回组合对象的逻辑。 对于数字来说,它们往往会被加到一起或者乘到一起。对于字符串来说,它们往往是被追加到一起。

语法:arr.reduce(callback [, initialValue]);

参数
•callback():此函数把两个对象合并成一个对象,并将其返回。参数有: ◦previousValue:上一次回调函数被调用时返回的值,或者是初始值(如果有的话)
◦currentValue:数组当前正在处理的元素
◦index:数组中当前元素的序数
◦array:当前正在处理的数组

•initialValue:可选。第一次回调所传入参数的初始值

例子

var numbers = [1, 2, 3, 4];

// 把数组中所有的值加起来
console.log([1, 2, 3, 4, 5].reduce(function(x, y) {
 return x + y
}, 0));

// 查找数组中最大的值
console.log(numbers.reduce(function(a, b) {
  return Math.max(a, b) // max()函数只能有两个参数
 }) 
);

其它函数

map()、filter()和reduce()函数在我们辅助函数的工具箱里并不孤单。这里还有更多的函数几乎在所有函数式应用里都会被使用。

Array.prototype.forEach

forEach()函数本质上是map()函数的非纯版本,它会遍历整个数组,并对每个元素应用回调。 然而这些回调函数不返回值。它是实现for循环的一个更纯粹的方式。

语法:arr.forEach(callback [, thisArg]);

参数:
•callback():对数组中每一个元素所应用的。参数有: ◦currentValue:数组中当前正在处理的元素
◦index:数组中当前元素的序数
◦array:正在处理的数组

•thisArg:可选。回调函数中作为this的值

例子:

var arr = [1, 2, 3];
var nodes = arr.map(function(x) {
 var elem = document.createElement("div");
 elem.textContent = x;
 return elem;
});

// 对每一个元素的值输出日志
arr.forEach(function(x) {
 console.log(x)
});

// 把节点追加到DOM上
nodes.forEach(function(x) {
 document.body.appendChild(x)
});

Array.prototype.concat

如果不用for或while处理数组,你会经常需要把数组拼接起来。另一个Javascript内建函数concat就是专门干这事儿的。 concat函数会返回一个新数组但不改变旧数组。它可以把你传入的所有参数拼接到一起。
console.log([1, 2, 3].concat(['a','b','c']) // 拼接两个数组
// Output: [1, 2, 3, 'a','b','c']

它返回两个数组拼接成的数组,同时原来的那些数组没有被改变。这就意味着concat函数可以链式调用。

var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [7,8,9];
var x = arr1.concat(arr2, arr3);
var y = arr1.concat(arr2).concat(arr3));
var z = arr1.concat(arr2.concat(arr3)));
console.log(x);
console.log(y);
console.log(z);

变量x、y、z的值最后都是[1,2,3,4,5,6,7,8,9]。

Array.prototype.reverse

这个Javascript内建函数是用于数组变形的。reverse函数用于将一个数组反转,也就是第个一元素会跑到最后, 而最后一个元素变成了第一个元素。

然而,这个函数并不会返回一个新的数组,而是把原来的数组替换掉了。我们可以做个更好的。下面是一个纯的反转数组函数

var invert = function(arr) {
 return arr.map(function(x, i, a) {
  return a[a.length - (i + 1)];
 });
};
var q = invert([1, 2, 3, 4]);
console.log(q);

Array.prototype.sort

与map()、filter()和reduce()函数相似,排序函数sort()需要传入一个回调函数来定义数组如何排序。 但是,跟reverse()一样,它也会把原来的数组替换。这可不太好。
arr = [200, 12, 56, 7, 344];
console.log(arr.sort(function(a,b){return a–b}) );
// arr现在是: [7, 12, 56, 200, 344];

我们可以写一个纯函数的sort(),但是排序算法的源代码很麻烦。对于特别大的数组,应当根据特定的数据结构来选用适合的算法, 比如快速排序、合并排序、冒泡排序等等。

Array.prototype.every 和 Array.prototype.some

Array.prototype.every() 和 Array.prototype.some() 都是纯的高阶函数,它们是Array对象的方法, 通过回调函数根据数组各元素返回的布尔值(或相当于布尔的值)来进行测试。如果数组中所有的元素通过回调函数计算都返回True, every()函数就返回true;如果数组中有一个元素返回True,some()函数就返回True。

例子:

function isNumber(n) {
 return !isNaN(parseFloat(n)) && isFinite(n);
}
console.log([1, 2, 3, 4].every(isNumber)); // Return: true
console.log([1, 2, 'a'].every(isNumber)); // Return: false
console.log([1, 2, 'a'].some(isNumber)); // Return: true

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn