logo
JR Academy · Blog职业洞察

如何操作JS的Array和Object

你还在用for循环数组或者object吗,太low了,Simplify your JavaScript – Use .map(), .reduce(), and .filter()如何操作JS的Array和Object ,教你如何用reduce, object value, includes, array.from, filter, keys, ent...

发布日期
阅读时长2 分钟
作者

This article is pointed towards beginners in Javascript or people who are just starting working with functional Javascript and never heard of map, filter and reduce. 

What is functional programming?

Functional programming is a programming paradigm where the output value of a function depends only on the arguments that are passed to the function, so calling a function a determinate amount of times will always produce the same result, no matter the amount of times you call it. This contrasts with a lot of common and contemporary code, where a lot of functions work with a local or global state, which may end up returning different results at different executions. A change in that state is a side-effect and, eliminating these, can make it easier to understand and predict the behavior of your code.

Why map, filter, reduce?

One of the key foundations of functional programming is its use of lists and list operations. In Javascript we have mapfilter and reduce, all functions that given an initial list (array of things), transform it into something else, while keeping that same original list intact.

Simplify your JavaScript – Use .map(), .reduce(), and .filter()

.map()

Creates a new array by manipulating the values in another array. Great for data manipulation and it is often used in React because it is an immutable method.

Let me explain how it works with a simple example. Say you have received an array containing multiple objects – each one representing a person. The thing you really need in the end, though, is an array containing only the id of each person.

How to use it?

This is the most basic way to call map

Create an array that adds a $ to the beginning of each number.

const numbers = [2, 3, 4, 5];
const dollars = numbers.map( number => '$' + number);
// dollars will be equal to ['$2', '$3', '$4', '$5']

This is the most basic way to call map

javascript 

As you can see, map receives a callback as an argument. That callback is then given the current value of the iteration, the index of the iteration and the original array from which map was called. There is also an optional second argument for map (after the callback) that is the value to use as “this” inside the callback.

 

 

 

作者Wang Yanbo
一键分享或复制链接
Wang Yanbo
Wang Yanbo

匠人学院,全球华人学习 AI 第一站

查看该作者的更多文章 →

相关文章推荐

查看全部文章 →