每个javascript数组方法

Arrays are an important aspect of any programming language, as we can store data inside from numbers, strings, objects, and even other arrays. Being able to work with arrays effectively is an important skill for any developer, no matter the programming language. JavaScript provides a lot of methods to make working on arrays easier.

数组是任何编程语言的重要方面,因为我们可以从数字,字符串,对象甚至其他数组中存储数据。 无论编程语言如何,有效地使用数组都是任何开发人员的一项重要技能。 JavaScript提供了许多方法来简化数组的工作。

We can define an array in the following ways:

我们可以通过以下方式定义数组:

Image for post
Array declaration
数组声明

Arrays are one of the data types present in JavaScript. They’re used to store data from any data types, but unlike objects in JavaScript (similar to the dictionary in Python), the index of each element matters.

数组是JavaScript中存在的数据类型之一。 它们用于存储任何数据类型的数据,但是与JavaScript中的对象(类似于Python中的字典)不同,每个元素的索引都很重要。

Even though arrays can be used to store data of any type, it’s often useful to store similar data in an array, like an array of users that signed up for an event or an array of to-do items. From the code snippet above, I’ve defined two methods you can use:

即使数组可用于存储任何类型的数据,将类似的数据存储在数组中通常也很有用,例如签署事件的用户数组或待办事项数组。 从上面的代码片段中,我定义了两种可以使用的方法:

  • Putting everything in a square brackets

    将所有内容放在方括号中
  • Using the Array constructor

    使用Array构造函数

The second method is rarely used, but it’s also useful. Let’s dive into the main objective of this article. I’m excited to walk you through some of these methods. I hope you’re also excited to begin.

第二种方法很少使用,但也很有用。 让我们深入探讨本文的主要目标。 我很高兴为您介绍这些方法。 希望您也很高兴开始。

Image for post
Photo by Japheth Mast on Unsplash
Japheth MastUnsplash拍摄的照片

数组方法 (Array Methods)

There are several methods that a JavaScript array has. This article will walk you through some of them.

JavaScript数组具有几种方法。 本文将引导您完成其中的一些操作。

I’ll start with the most common ones:

我将从最常见的几个开始:

Most of the time, given an array, you’ll want to add an element to the end or beginning, remove the first or last element. Implementing the following is somewhat easy.

在大多数情况下,给定一个数组,您将需要在末尾添加一个元素,删除第一个或最后一个元素。 实现以下内容有些容易。

推法 (The push method)

Image for post

The first method I’ll be talking about is the push method. This method simply adds an element to the end of the array and returns the length of the usersData array after adding the element. The code snippet above defines a usersData array, which mimics the result of a database/API call.

我要谈论的第一种方法是push 方法。 此方法只是将元素添加到数组的末尾,并在添加元素后返回usersData数组的长度。 上面的代码段定义了一个usersData数组,该数组模仿了数据库/ API调用的结果。

Then we create a new user, and we’d like to add this new user to our usersData. Instead of hardcoding the IDs, one way to deal with that without working with real databases is to set the value of the ID to be the length of the array before adding the element plus one.

然后,我们创建一个新用户,并将此新用户添加到usersData 。 无需对ID进行硬编码,一种不使用实际数据库进行处理的方法是将ID的值设置为数组的长度,然后再添加元素加一。

弹出方法 (The pop method)

Image for post

The pop method simply removes the last element of the array and returns that element.

pop方法只是删除数组的最后一个元素并返回该元素。

The code snippet above defines a usersData array that mimics the result of a database/API call. Then, we remove the last element of the data.

上面的代码段定义了一个模仿数据库/ API调用结果的usersData数组。 然后,我们删除数据的最后一个元素。

移位方法 (The shift method)

Image for post

The shift method, unlike the pop method, simply removes the first element of the array and returns that element. The code snippet above defines a usersData array, which mimics a the result of a database/API call.

pop方法不同, shift方法只是删除数组的第一个元素并返回该元素。 上面的代码段定义了一个usersData数组,该数组模拟了数据库/ API调用的结果。

不移位方法 (The unshift method)

Image for post

The unshift method, unlike the push method, simply adds an element to the beginning of the array and returns the length of the new array. The code snippet above defines a usersData array which mimics the result of a database/API call. I then created a new user object, which we want to add to the beginning of the array.

push方法不同, unshift方法只是将元素添加到数组的开头并返回 新数组的长度。 上面的代码段定义了一个usersData数组,该数组模拟了数据库/ API调用的结果。 然后,我创建了一个新的用户对象,我们要将其添加到数组的开头。

ES6方法 (ES6 Methods)

Image for post
ES6
ES6

ES6, which is the short form of ECMAScript 6, is the version of JavaScript that was released in June 2015. It seems the developers that maintain JavaScript like my birth month because that’s when most of their versions were released.

ES6是ECMAScript 6的缩写,是2015年6月发布JavaScript版本。似乎开发人员像我的出生月份一样维护JavaScript,因为这是大多数版本发布的时间。

If you’re just learning JavaScript, ES6 will make life much more easier for you. It provides not just array methods, but it also provides things like destructuring, arrow functions, a better way to write objected-oriented and modular code, among other things.

如果您只是学习JavaScript,ES6将使您的生活更加轻松。 它不仅提供数组方法,而且还提供诸如解构,箭头函数,更好的编写面向对象和模块化代码的方法之类的东西。

Most of these ES6 array methods take a callback function, and as a result they’re called higher-order array methods. Arrow functions are very common in higher-order functions, as it simplifies our code

这些ES6数组方法中的大多数都带有回调函数,因此它们被称为高阶数组方法。 箭头函数在高阶函数中非常常见,因为它简化了我们的代码

地图方法 (The map method)

If there’s any ES6 array method that you’ll use almost all the time, it’s this method. It’s my best array method both in JavaScript and Python. Even though some JavaScript developers have tried to implement map before ES6, the standard map method was introduced in JavaScript in ES6. In the code snippet below, I implemented the map in three ways:

如果几乎所有时间都使用ES6数组方法,那么就是这种方法。 无论是JavaScript还是Python,这都是我最好的数组方法。 即使某些JavaScript开发人员已尝试在ES6之前实现map ,但标准map 方法是在ES6JavaScript中引入的。 在下面的代码片段中,我以三种方式实现了map

  • Using regular JavaScript functions: Here I passed two arguments to the function, first item, which is the element I want to do something on, and an optional argument, index, which is the index of each element

    使用常规JavaScript函数:在这里,我向函数传递了两个参数,第一个是item ,这是我要在其上做的元素,另一个是可选参数index ,它是每个元素的索引

  • Using arrow functions: I also passed two arguments just like in the first example, but the callback function here is an arrow function, which makes the code a lot neater.

    使用箭头函数:与第一个示例一样,我也传递了两个参数,但是这里的回调函数是箭头函数,这使代码更加整洁。

  • I also used arrow functions, but I passed only one argument — the item that I want to iterate on. This is useful if I don’t need the index.

    我还使用了箭头函数,但只传递了一个参数-我要迭代的项目。 如果我不需要索引,这很有用。

If I wanted to implement this function without ES6 methods, I’d have to loop through the array natively using the standard for loop: for (let i = 0; i < arr.length; i++) {doSomething()}. But thanks to ES6, we can do this:

如果我想在没有ES6方法的情况下实现此功能,则必须使用标准的for循环在数组for循环: for (let i = 0; i < arr.length; i++) {doSomething()} 。 但是由于有了ES6,我们可以做到这一点:

Image for post

过滤方式 (The filter method)

The filter method is another higher-order array method that you should use today. What filter does is simple. Given an array of elements, we want to return a new array from the initial array, where a particular condition is true. The callback function must return a boolean, and the element that obeys the condition is what will be in the new array.

filter方法是您今天应该使用的另一种高阶数组方法。 filter作用很简单。 给定一个元素数组,我们想从初始数组返回一个新数组,其中特定条件为true 。 回调函数必须返回一个布尔值,并且满足条件的元素将是新数组中的内容。

Image for post

减少方法 (The reduce method)

This is very nice, and I think it’s the hardest of all the methods I’ve mentioned so far. What this method does is to use a particular callback to reduce the array. For example, if I want to find the sum of all of the elements in an array or the product of all of the elements in an array, this method is a nice method to use, instead of looping and incrementing the initial sum or product.

这非常好,我认为这是到目前为止我提到的所有方法中最困难的一种。 此方法的作用是使用特定的回调来减少数组。 例如,如果我要查找数组中所有元素的总和或数组中所有元素的乘积,则此方法是一种好用的方法,而不是循环并递增初始和或乘积。

Image for post

forEach方法 (The forEach method)

This method is similar to the map method, but in this case, it doesn’t return a new array. It’s more of the regular for loop in JavaScript but in a cleaner and more advanced way. It takes three parameters, as you might have known. The first is the item in the array, the second is the index of the item (which is optional), and the third is the array object the current element belongs to.

该方法类似于map方法,但是在这种情况下,它不会返回新的数组。 它更像是JavaScript中的常规for循环,但是以一种更干净,更高级的方式。 如您所知,它包含三个参数。 第一个是数组中的项目,第二个是项目的索引(可选),第三个是当前元素所属的数组对象。

In the code snippet below, I used forEach to manipulate the Document Object Model (DOM), which is pretty cool. I can update the array, and the list items rendered on the DOM will be changed automatically.

在下面的代码片段中,我使用了forEach操作文档对象模型(DOM),这很酷。 我可以更新数组,并且在DOM上呈现的列表项将自动更改。

Image for post

concat方法 (The concat method)

There are cases where you’ll want to join or merge two or more arrays together. Then, this function will be very handy. Calling concat on two arrays produces a new array that consists of the two arrays combined.

在某些情况下,您需要将两个或多个数组合并或合并在一起。 然后,此功能将非常方便。 在两个数组上调用concat会产生一个新数组,该数组由两个数组组合而成。

Image for post

每种方法 (The every and some methods)

These methods are useful if you want to know if all the elements in an array pass a condition and if some of the elements in an array pass a condition, respectively.

如果您想知道数组中的所有元素是否都通过条件以及数组中的某些元素是否分别通过条件,则这些方法很有用。

Image for post

Other methods include:

其他方法包括:

The fill method

填充方法

Fills every element in the array with a value that’s passed as a parameter: [1, 2, 3, 4].fill(1) // [1, 1, 1, 1].

用作为参数传递的值填充数组中的每个元素: [1, 2, 3, 4].fill(1) // [1, 1, 1, 1] [1, 2, 3, 4].fill(1) [1, 1, 1, 1]

The entries method

报名方法

This makes the array behave like an object with a key-value pair, where the key is the index and the value is the element.

这使数组的行为类似于带有键-值对的对象,其中键是索引,值是元素。

The find method

查找方法

This method returns the first element in an array that passes a test. It takes a callback function, which returns a boolean.

此方法返回通过测试的数组中的第一个元素。 它需要一个回调函数,该函数返回一个布尔值。

The splice method

拼接方法

This method takes an infinite number of parameters — the first two being the index where you want to start inserting and removing elements and the number of elements that you want to remove, respectively — and the remaining parameters being the elements that you want to add to the array. It returns an array of the elements removed and mutates the array.

此方法采用无限数量的参数-前两个参数分别是您要开始插入和删除元素的索引以及要删除的元素数-其余参数是要添加到的元素数组。 它返回删除的元素的数组并对该数组进行突变。

The reverse method

反向方法

The reverse method reverses the array. Note that it mutates it, meaning it changes the array instead of just creating the copy of it.

反向方法反转数组。 请注意,它会对其进行突变,这意味着它会更改数组,而不仅仅是创建其副本。

Image for post

The join method

联接方法

This method turns an array to an array to a string. Note that it doesn’t mutate the array — it just creates a copy of it. The reverse of this method is the split method, which turns a string to an array. It takes a string as a parameter, which is what will be used to join each element of the array.

此方法将数组转换为字符串数组。 请注意,它不会更改数组,而只是创建它的副本。 此方法的相反方法是split方法,它将字符串转换为数组。 它以字符串作为参数,这将用于连接数组的每个元素。

The flat method

平面法

The flat method is a new method that was added in ES11 (ES11 was created this June). This method flattens an array.

flat方法是ES11中添加的新方法(今年11月创建了ES11)。 此方法展平数组。

Let’s say we have an array that contains an array, and we want to find the sum and product of every element in the arrays inside the array. What I mean is that if I have an array which is defined by [[1, 2], [3, 4]], the sum should be 10 and the product should be 24.

假设我们有一个包含数组的数组,并且我们想要找到数组内部数组中每个元素的总和和乘积。 我的意思是,如果我有一个由[[1, 2], [3, 4]]定义的数组,则总和应为10 ,乘积应为24

One way to go about this is to loop through the initial array and loop through each element and get the sum and product.

一种解决方法是遍历初始数组并遍历每个元素并获得总和与乘积。

With ES6, I can loop through the initial array and use the reduce method to get the sum and product of each element in the main array — using that to get the total sum and product. But with the flat array, I can flat the main array, thus returning a single array containing only numbers, and I can use the reduce method on it.

使用ES6,我可以遍历初始数组,并使用reduce方法获取主数组中每个元素的总和与乘积,然后使用该方法获取总和与乘积。 但是使用flat数组,我可以对主数组进行平面化,从而返回仅包含数字的单个数组,并且可以在其上使用reduce方法。

The flatMap method

flatMap方法

This is the combination of flat and map. It maps each element in the array to a given callback function then flattens the resulting array.

这是flatmap的组合。 它将数组中的每个元素映射到给定的回调函数,然后展平结果数组。

Let’s say we’d like to get the square of each element in a nonflattened array, and we’d like to flatten it. This method will make life easier for us. In the part where I used the flatMap method in the code snippet below, it takes an element that’s an array, and I returned a new array, which is the square of the elements. And finally, it flattens the resulting array.

假设我们想要在非展平数组中获得每个元素的平方,并且我们想展平它。 这种方法将使我们的生活更轻松。 在下面的代码片段中使用flatMap方法的部分中,它采用了一个元素,该元素是一个数组,并且我返回了一个新数组,它是元素的平方。 最后,它使结果数组变平。

Image for post

结论 (Conclusion)

This article has walked you through some of the JavaScript array methods. Believe me there are more methods. Is there any other method that you’d like to add to the list?

本文向您介绍了一些JavaScript数组方法。 相信我还有更多方法。 您还想将其他方法添加到列表中吗?

Happy hacking!

骇客骇客!

翻译自: https://medium.com/better-programming/every-javascript-array-method-a50905f916bd

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值