JavaScript中最重要的数组方法

Array is a very special concept in any programming language. All the major programming languages support the array data structure. Before going into the technicalities of the array from a programming point of view, let’s try to understand what an array is from a common man’s perspective.

在任何编程语言中,数组都是一个非常特殊的概念。 所有主要的编程语言都支持数组数据结构。 从编程的角度介绍数组的技术之前,让我们尝试从普通人的角度理解数组是什么。

Have you ever seen a school assembly? It is pretty obvious, you have seen it and in childhood all of us have been part of that boring event. In the assembly hall, students of the same class or section sit together in one row, isn’t it. That is a bare minimum real-life example of an array.

你见过学校集会吗? 很明显,您已经看到了这一点,在我们的童年时代,我们所有人都参与了这一无聊的活动。 在礼堂里,同班或同班的学生排成一排,不是吗。 那是数组的最低限度的真实示例。

Another example could be the color pencil box which all of us have used for coloring pictures. In that pretty little box, the items share something in common. They are all used for giving colors, right. So, in the perspective of programming, we can say array is a collection of items which are related to each other.

另一个例子可能是彩色铅笔盒,我们所有人都用它来给图片着色。 在那个很小的盒子里,这些物品有一些共同点。 它们全都用来给颜色上色。 因此,从编程的角度来看,我们可以说数组是彼此相关的项的集合。

The arrangement of the items inside an array leads to a particular structure because of which arrays are called a special type of data structure. The term data structure refers to an arrangement of data in such a way that setting, and retrieval of items is very simple, and they follow a certain pattern.

数组内部项目的排列导致特定的结构,因为哪些数组被称为特殊类型的数据结构。 术语“数据结构”是指数据的排列方式,使得项目的设置和检索非常简单,并且它们遵循一定的模式。

An array essentially can just contain simple data elements like numbers and strings or in more complex scenarios, they can contain complex objects. In javaScript particularly, arrays are hashtable based and they not necessarily are placed in contiguous memory locations.

数组本质上只能包含简单的数据元素,例如数字和字符串,或者在更复杂的情况下,它们可以包含复杂的对象。 特别是在javaScript中,数组是基于哈希表的,因此不必将它们放置在连续的内存位置。

JavaScript arrays are index based and we can set and fetch items based on their indices. JavaScript essentially does not support the concept of associative arrays which means it does not fetch or set array items through keys or simple terms strings.

JavaScript数组是基于索引的,我们可以根据它们的索引来设置和获取项目。 JavaScript本质上不支持关联数组的概念,这意味着它不通过键或简单术语字符串来获取或设置数组项。

The simplest way to initialize an array in JavaScript is

在JavaScript中初始化数组的最简单方法是

var arr = [];

If you want to store some items, say some numbers in the array, we can initialize it as follows.

如果要存储一些项目,例如在数组中说一些数字,我们可以按以下方式对其进行初始化。

var arr = [1,2,3,4,5];

In case you want to store some objects in the array, it will be like the below code snippet. In this case the array is also known as Array of Objects.

如果要在数组中存储一些对象,将类似于下面的代码片段。 在这种情况下,该数组也称为对象数组。

var arr = [ 
{ name: 'Satya', age: 28 },
{ name: 'Priya', age: 24 },
{ name: 'Mishra', age: 23 }
];

JavaScript arrays are zero indexed. What does that mean and why is it so. Let’s see in a while.

JavaScript数组的索引为零。 这是什么意思,为什么会这样。 让我们稍等一下。

Zero indexed simply means that the index of the first element of an JavaScript array starts from 0 just like C and C++.There are other programming COBOL, FORTRAN, R, Julia etc. which do not follow this convention. This happens for JavaScript because of the design of the programming language. When we say we want to access the first element of the array, by design, the first element resides at a place which is referenced by the array variable itself. So here the index is not pointing to the memory position of the element, but rather it points to the offset of the element from the initial memory location pointed to by the variable. Clear, Huh. Now let’s explore some important properties and methods of array data structure in JavaScript.

零索引只是意味着JavaScript数组的第一个元素的索引从0开始,就像C和C ++一样。还有其他编程的COBOL,FORTRAN,R,Julia等不遵循此约定。 由于编程语言的设计,JavaScript会发生这种情况。 当我们说要通过设计访问数组的第一个元素时,第一个元素位于数组变量本身引用的位置。 因此,这里的索引不是指向元素的存储位置,而是指向元素与变量所指向的初始存储位置之间的偏移量。 知道了 现在让我们探索JavaScript中一些重要的属性和数组数据结构的方法。

length

长度

The length property gives the count of the items present in the array. It is a very important property as it is very helpful while iterating over an array. The index of the last item in the array is 1 less than the length.

length属性给出了数组中存在的项目数。 这是非常重要的属性,因为在遍历数组时非常有帮助。 数组中最后一项的索引比长度小1。

var arr = [1, 2, 3, 4, 5]; 
console.log(arr.length); // 5

To get the last item we can do like;

要获得最后一件商品,我们可以做;

arr[arr.length - 1] // 5

For iterating over the array, we can run a for loop through the array with the length property coming in as a condition.

为了遍历数组,我们可以在数组中运行一个for循环,并将length属性作为条件。

for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

push ():

推 ():

push method is used to add a new array element at the end of the array. Pretty straightforward. Let’s see the syntax.

push方法用于在数组末尾添加新的数组元素。 非常简单。 让我们看看语法。

var arr = [1,2,3,4,5]; 
arr.push(6);
console.log(arr); // [1, 2, 3, 4, 5, 6]

pop ():

弹出():

pop method is used to remove the last item from an array. We can even empty an array with this method if we run a loop on the array for a count equal to the length of the array and pop each element from it. The pop() method returns the popped value.

pop方法用于从数组中删除最后一项。 如果我们在数组上循环一个等于数组长度的计数并从中弹出每个元素,我们甚至可以使用此方法清空数组。 pop()方法返回弹出的值。

var arr = [1, 2, 3, 4, 5]; 
var len = arr.length;
for (var i = 0; i < len; i++) {
arr.pop();
}

shift ():

移():

The shift () method is used to remove an element from the beginning of an array. It returns the removed element after the operation.

shift()方法用于从数组的开头删除元素。 在操作之后,它返回移除的元素。

var arr = [1, 2, 3, 4, 5]; 
arr.shift();

unshift ():

取消移位():

The unshift method is used to add a new item at the beginning of the array. It returns the length of the final array.

unshift方法用于在数组的开头添加新项。 它返回最终数组的长度。

var arr = [1, 2, 3, 4, 5]; 
arr.unshift(0);

delete ():

删除():

The delete method is used to delete an array entry as follows.

delete方法用于删除数组条目,如下所示。

var arr = [1, 2, 3, 4, 5]; 
delete arr[2];
console.log(arr); // [1, 2, empty, 4, 5]

It returns a Boolean true or false depending upon if the deletion operation was successfully conducted or not. The deleted item shows as empty in the array and the length of the array remains unaffected. That happens because though there is no item present in the particular memory location, still it gets counted in the length of the array.

根据删除操作是否成功执行,它返回布尔值true或false。 删除的项目在数组中显示为空,并且数组的长度不受影响。 发生这种情况的原因是,尽管在特定的内存位置中没有项目,但仍会在数组的长度中对其进行计数。

splice ():

拼接():

The splice method removes array items and replaces new items if provided. The syntax of the splice() method is as follows.

拼接方法删除数组项并替换新项(如果提供)。 splice()方法的语法如下。

splice (starting index to remove item, number of items to remove, replacement items);

拼接(开始删除项目的索引,要删除的项目数,替换项目);

The third parameter is optional.

第三个参数是可选的。

var arr = [1, 2, 3, 4, 5]; 
arr.splice(1, 2);
console.log(arr); // [1, 4, 5]

With replacement items by providing the third parameter, we can remove the item first and replace it with new items.

通过提供第三个参数来替换项目,我们可以先删除该项目,然后将其替换为新项目。

var arr = [1, 2, 3, 4, 5]; 
arr.splice(1, 2, 9, 10);
console.log(arr); // [1, 9, 10, 4, 5]

If given a negative index, the splice operation is conducted from the end of the array.This method returns a new array containing the removed items.

如果给定一个负索引,则从数组末尾进行拼接操作。此方法返回一个包含删除项的新数组。

Slice ():

片():

This method returns a new array containing the specified items except the last index provided.

此方法返回一个新数组,其中包含指定的项目(最后提供的索引除外)。

arr = [1, 2, 3, 4, 5]; 
arr.slice(1, 3); // [2, 3]

concat ():

concat():

The concat method merges more than two arrays or values into a single array and returns the new array. The new array is serialized according to the original arrays.

concat方法将两个以上的数组或值合并到一个数组中,并返回新数组。 新阵列将根据原始阵列进行序列化。

var arr1 = [1, 2]; 
var arr2 = [3, 4];
arr1.concat(arr2); // [1,2,3,4]

The order of the concat operation matters and the sequence changes as demonstrated in the following code snippet.

concat操作的顺序很重要,并且序列会更改,如以下代码片段所示。

var arr1 = [1, 2]; 
var arr2 = [3, 4];
arr2.concat(arr1); // [3,4,1,2]

The concat method also takes individual values as arguments like below.

concat方法还采用单个值作为自变量,如下所示。

var arr1 = [1, 2]; 
var arr2 = [3, 4];
arr1.concat(arr2, 5, 6); // [1,2,3,4,5,6]

forEach():

forEach():

The forEach method is used to iterate over an array. It is native to the Array prototype. The advantages of forEach loop above are

forEach方法用于遍历数组。 它是Array原型的本机。 上面的forEach循环的优点是

  • it has a clear syntax

    它具有清晰的语法
  • the forEach method keeps the variables from the callback function bound to the local scope

    forEach方法将回调函数中的变量绑定到本地范围
  • the forEach is less error prone

    forEach不太容易出错

An example of the forEach method is given below.

下面给出了forEach方法的示例。

arr = [1,2,3,4,5];
arr.forEach((item, index) => {
console.log(`${item} is at index ${index}`);
});
// 1 is at index 0
// 2 is at index 1
// 3 is at index 2
// 4 is at index 3
// 5 is at index 4

indexOf ():

指数 ():

This method returns the position of the first occurrence of the item in the array. If the provided item is not part of the array, then it returns -1. Due to this feature, this method is used to check if an item is present in the array.

此方法返回数组中第一次出现该项目的位置。 如果提供的项目不属于数组,则返回-1。 由于此功能,此方法用于检查数组中是否存在项目。

First let’s check a very simple example.

首先,让我们检查一个非常简单的示例。

var arr = [1, 2, 3, 4, 5]; 
arr.indexOf(3); //2

To check if an element is present in the array, we can do like,

要检查数组中是否存在元素,我们可以这样做,

var arr = [1, 2, 3, 4, 5];
if (arr.indexOf(item) > -1) {
// Code to be executed when item is present
}

lastIndexOf ():

lastIndexOf():

The lastIndexOf method returns the last occurrence of the item in the array. It essentially searches from the end of the array.

lastIndexOf方法返回该项目在数组中的最后一次出现。 它实质上是从数组末尾开始搜索。

var arr = [1, 2, 3, 4, 1, 6]; 
arr.lastIndexOf(1); // 4

includes ():

包括():

This method checks if an item is present in the array and returns a Boolean.

此方法检查数组中是否存在某项并返回布尔值。

var arr = [1, 2, 3, 4, 5]; 
arr.includes(2); // true

find ():

找 ():

The find method is used to find a particular item in an array. This method is very useful particularly when you are dealing with an array of objects. We pass a condition for this method and it selects the first element that matches the condition. If no item matches the condition, then it gives undefined.

find方法用于在数组中查找特定项。 该方法在处理对象数组时特别有用。 我们为此方法传递一个条件,它选择与条件匹配的第一个元素。 如果没有项目符合条件,则给出未定义。

var students = [ 
{ roll: 1, name: "John" },
{ roll: 2, name: "Pete" },
{ roll: 3, name: "Mary" }
];
var student = students.find(student => student.roll == 2); console.log(student.name); // {roll: 2, name: "Pete"}

findIndex ():

findIndex():

This method returns the index of the found element instead of the entire object and if no item matches the condition, then it returns -1.

此方法返回找到的元素的索引,而不是整个对象的索引,如果没有项目与条件匹配,则它返回-1。

var students = [ 
{ roll: 1, name: "John" },
{ roll: 2, name: "Pete" },
{ roll: 3, name: "Mary" }
];
var student = students.find(student => student.roll == 2); console.log(student.name); // 1

map ():

地图():

The map () function is used for array transformation. It takes another custom function as an argument and on each array item, applies that function. The function provided as an argument can be a conventional vanilla JavaScript function or it may be an arrow function.

map()函数用于数组转换。 它使用另一个自定义函数作为参数,并在每个数组项上应用该函数。 作为参数提供的函数可以是常规JavaScript函数,也可以是箭头函数。

var arr = [1, 2, 3, 4, 5]; 
arr.map(function (item) { console.log(item + 1); });

Sort ():

排序():

The sort method as the name suggests is used to sort an array. A simple issue with the sort method is that it sorts the items by their corresponding string ASCII values thereby giving inaccurate results sometimes.

顾名思义,sort方法用于对数组进行排序。 sort方法的一个简单问题是,它按项目的相应字符串ASCII值对项目进行排序,从而有时会得出不正确的结果。

To overcome this problem, we pass a callback function as an argument which compares elements and gives the exact result. A simple use of the sort method is as follows.

为了克服这个问题,我们传递了一个回调函数作为参数,该参数比较元素并给出准确的结果。 排序方法的简单用法如下。

arr = [3, 2, 3, 4, 2, 2, 7]; 
arr.sort(function (a, b){ return a - b; });//ascending order sorting

We can also do a descending order of sorting just by reversing the return value of the callback function. An example of a descending order sorting can be as follows.

我们也可以仅通过反转回调函数的返回值来进行降序排序。 降序排序的示例可以如下。

arr.sort(function (a, b) {
return b - a;
});// descending order sorting

Reverse ():

逆转 ():

This method is used to reverse an array. It is a very straightforward method.

此方法用于反转数组。 这是一个非常简单的方法。

var arr = [1, 2, 3, 4, 5]; 
arr.reverse();

reduce ():

减少 ():

This method is used to reduce the array into a single value.

此方法用于将数组简化为单个值。

function sum(total, num) { 
return total + num;
}
var arr = [1, 2, 3, 4, 5];
numbers.reduce(sum); // 15

isArray ():

isArray():

This method returns a Boolean stating if the provided variable is an array or not. If the value is an array it returns a true, else it returns false.

此方法返回一个布尔值,说明提供的变量是否为数组。 如果值是数组,则返回true,否则返回false。

var arr = [1, 2, 3, 4, 5]; 
Array.isArray(arr); // true
Array.isArray({}); // false

These are pretty much the mostly needed array methods.

这些几乎是最需要的数组方法。

翻译自: https://medium.com/swlh/most-important-array-methods-in-javascript-ee509ab61cfd

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在前端面试,经常会被问到关于JavaScript数组方法。下面是一些常见的数组方法: 1. `push()`:向数组末尾添加一个或多个元素,并返回新数组的长度。 2. `pop()`:删除并返回数组的最后一个元素。 3. `shift()`:删除并返回数组的第一个元素。 4. `unshift()`:向数组的开头添加一个或多个元素,并返回新数组的长度。 5. `concat()`:将两个或多个数组合并成一个新数组。 6. `slice()`:返回指定索引范围内的元素,不会修改原数组。 7. `splice()`:从指定位置删除或替换元素,并返回被删除的元素。 8. `join()`:将数组的所有元素以指定的分隔符连接成一个字符串。 9. `indexOf()`:返回指定元素在数组首次出现的索引,如果不存在则返回-1。 10. `lastIndexOf()`:返回指定元素在数组最后一次出现的索引,如果不存在则返回-1。 11. `forEach()`:对数组的每个元素执行指定的操作。 12. `map()`:对数组的每个元素执行指定的操作,并返回一个新数组。 13. `filter()`:根据指定条件过滤数组的元素,并返回一个新数组。 14. `reduce()`:对数组的所有元素执行指定的累加器函数,返回一个累计值。 15. `sort()`:对数组进行排序,默认按照Unicode编码顺序进行排序。 16. `reverse()`:颠倒数组元素的顺序。 17. `find()`:返回数组满足指定条件的第一个元素。 18. `findIndex()`:返回数组满足指定条件的第一个元素的索引。 19. `some()`:检测数组是否至少有一个元素满足指定条件。 20. `every()`:检测数组的所有元素是否都满足指定条件。 以上只是一些常见的数组方法,还有许多其他方法可以用于对数组进行操作和处理。在面试,了解这些常用方法并能够灵活运用是很重要的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值