search
HomeWeb Front-endJS Tutorialjavascript functional programming programmer's toolset_javascript skills

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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.