Array methods
JavaScript Array methods (JavaScript数组方法)
In JavaScript, there exist a wide range of array methods. To give you more detailed and comprehensive information, we are going to split them into groups. (在JavaScript中,存在各种各样的数组方法。为了给您提供更详细和全面的信息,我们将把它们分成几组。)
Add/Remove Methods
Add/Remove Methods (添加/删除方法)
In chapter Arrays, we have already spoken about this group of methods. Among them are:
arr.push(…items)- helps to add items to the end;
arr.pop()- extracting an item from the end;
arr.shift()- extracting an item from the beginning;
arr.unshift(…items)- adding items to the beginning. (- arr.unshift (… items) -将项目添加到开头。)
In this chapter, we will speak about several other methods. (在本章中,我们将讨论其他几种方法。)
Splice
Splice ( 接合)
The first method is the arr.splice. It is used for adding or removing items to/from the array, as well as for returning the already removed ones. So, with this method, you can do anything: insert, remove, replace elements.
The syntax looks like this:
arr.splice(index[, deleteCount, elem1, ..., elemN])
It is easier to grasp by example. (通过示例更容易掌握。)
In the first example, the deletion is demonstrated as follows:
let arr = ["Welcome", "to", "w3cdoc"];
arr.splice(1, 1); // from index 1 remove 1 element
console.log(arr); // ["Welcome", "w3cdoc"]
In the next example, we’ll remove three elements and replace them with the other two:
let arr = ["Welcome", "to", "w3cdoc", "Javascript", "book"];
// remove 3 first elements and replace them with another
arr.splice(0, 3, "Starts", "read");
console.log(arr) // now ["Starts", "read", "Javascript", "book"]
Now, you can notice that splice returns the array of the removed elements, as follows:
let arr = ["Welcome", "to", "w3cdoc", "Javascript", "book"];
// remove 2 first elements
let removed = arr.splice(0, 2);
console.log(removed); // "Welcome", "to" <-- array of removed elements
It is essential to know that with this method, you can also insert elements without any removals. To do so, it is necessary to set deleteCount to 0 , like this:
let arr = ["Welcome", "to", "w3cdoc"];
// from index 2, delete 0
// then insert "Javascript" and "book"
arr.splice(4, 0, "Javascript", "book");
console.log(arr); // "Welcome", "to", " w3cdoc", "Javascript", "book"
Slice
Slice (扇面)
arr.slice is a simple method, much simpler than arr.splice. (arr.slice是一种简单的方法,比arr.splice简单得多。)
Its syntax is the following:
arr.slice([start], [end])
This method returns a new array copying to it all the items from index start to the end (but it doesn’t include the end). If both the start and the end are negative position from the array, the end will be assumed. (此方法返回一个新的数组,将从索引开始到结束的所有项目复制到它(但它不包括结束)。如果开始和结束都是数组的负位置,则假定结束。)
It’s much like end method, but it makes subarrays instead of substrings. (它很像结束方法,但它会生成子数组而不是子字符串。)
Here is an example:
let arr = ["W", "3", "D", "o", "c", "s"];
console.log(arr.slice(1, 3)); // 3,D (copy from 1 to 3)
console.log(arr.slice(-2)); // c,s (copy from -2 till the end)
You can call it without arguments: str.slice will create a copy of arr.
Concat
Concat (CONCAT)
The arr.concat method is used for creating a new array, including values from other arrays, as well as additional items. The syntax will look like this:
arr.concat(arg1, arg2...)
It will accept arguments at any quantity (arrays or values). (它将接受任何数量的参数(数组或值)。)
The result will be a new array with the items from arr, then arg1, arg2, and more. (结果将是一个包含arr、arg1、arg2等项的新数组。)
In case an argument argN represents an array, all its elements will be copied. In other cases, the argument will be copied. (如果参数argN表示数组,则将复制其所有元素。在其他情况下,参数将被复制。)
For example:
let arr = ["a", "b"];
// create an array from: arr and ["c", "d"]
console.log(arr.concat(["c", "d"])); // a,b,c,d
// create an array from: arr and ["c", "d"] and [e,f]
console.log(arr.concat(["c", "d"], ["e", "f"])); // a,b,c,d,e,f
// create an array from: arr and ["c", "d"], then add values e and f
console.log(arr.concat(["c", "d"], "e", "f")); // a,b,c,d,e,f
Iterate: forEach
Iterate: forEach
The method arr.forEach allows running a function for each element of the array. (Arr.forEach方法允许为数组的每个元素运行一个函数。)
Here is the syntax:
arr.forEach(function (item, index, array) {
// ... do something with item
});
In the following example, each element of the array is shown:
// for each element call alert
["dog", "cat", "mouse"].forEach(alert);
Searching in the array
Searching in the array (在数组中搜索)
In this part, we will cover the methods for searching in an array. (在本部分中,我们将介绍在数组中搜索的方法。)
indexOf/lastIndexOf and includes
indexOf/lastIndexOf and includes (indexOf/lastIndexOf和包含)
These methods have the same syntax doing the same as their string counterparts. The difference is that they operate on items, not on characters. (这些方法具有与字符串对应方法相同的语法。不同之处在于,它们对物品进行操作,而不是对角色进行操作。)
What they do:
arr.indexOf(item, from) searches for an item beginning from the index from and returns it to where it was found, otherwise -1. (- arr.indexOf (item, from)从索引开始搜索项目,并将其返回到找到的位置,否则为-1。)
arr.lastIndexOf(item, from) is similar, but searches from right to left. (- arr.lastIndexOf (item, from)类似,但从右到左进行搜索。)
arr.includes(item, from) searches for an item, beginning from the index from, and returns true, if it was found. (- arr.includes (item, from)从索引from开始搜索项目,如果找到则返回true。)
Let’s check out the following example:
let arr = [1, 0, false];
console.log(arr.indexOf(0)); // 1
console.log(arr.indexOf(false)); // 2
console.log(arr.indexOf(null)); // -1
console.log(arr.includes(1)); // true
Take into account that these methods use comparison ===. Thus, when you look for false, it will find false and not zero. (请考虑这些方法使用比较= = =。因此,当您查找false时,它会找到false而不是零。)
Find and FindIndex
Find and FindIndex (查找和FindIndex)
Let’s see that you have an array with objects and want to find an object with a specific condition. Then you need to use the arr.find(fn) method using this syntax:
let result = arr.find(function (item, index, array) {
// if true is returned,the item is returned, and iteration is stopped
(//如果返回true ,则返回项,并停止迭代)
// for falsy scenario returns undefined
});
The function will be called for the array elements, one after another, like this:
An item is an element. (-项目是一个元素。)
The index will be its index. (-索引将是其索引。)
The array will be the array itself. (-数组将是数组本身。)
In the event of returning true, the search will be stopped, and the item- returned. (如果返回true ,搜索将停止,商品将返回。)
For instance:
let animals = [{
id: 1,
name: "dog"
},
{
id: 2,
name: "cat"
},
{
id: 3,
name: "mouse"
}
];
let animal = animals.find(item => item.id == 1);
console.log(animal.name); // dog
Filter
Filter (过滤)
This method searches for the first element that makes the function return true. (此方法搜索使函数返回true的第一个元素。)
In case there are many elements, you can use the arr.filter(fn) method. Its syntax looks like find, but the filter will return an array with all the matching elements:
let results = arr.filter(function (item, index, array) {
// if true item is pushed to results and the iteration continues
(//如果true项被推送到结果并且迭代继续)
// returns empty array if nothing found
});
Here is an example:
let animals = [{
id: 1,
name: "dog"
},
{
id: 2,
name: "cat"
},
{
id: 3,
name: "mouse"
}
];
// returns array of the first two animals
let someAnimals = animals.filter(item => item.id < 3);
console.log(someAnimals.length); // 2
Transforming an array
Transforming an array (转换数组)
In this part, we will cover the methods targeted at transforming and reordering an array. (在本部分中,我们将介绍转换和重新排序数组的方法。)
map
map (n.地图)
This method is one of the most useful and frequently used ones. Here is the syntax:
let result = arr.map(function (item, index, array) {
// returns the new value instead of item
});
In this example, each element is transformed into its length:
let lengths = ["dog", "cat", "mouse"].map(item => item.length);
console.log(lengths); // 3,3,5
sort(fn)
sort(fn) (sort (fn))
This method is used for sorting the array in place, changing the element order. (此方法用于对数组进行就地排序,更改元素顺序。)
Let’s have a look at the following example:
let arr = [1, 3, 25];
// the method reorders the content of arr
arr.sort();
console.log(arr); // 1, 25, 3
You will find something quite strange in the outcome. The order looked like 1, 25, 3 (你会在结果中发现一些非常奇怪的东西。订单看起来像1、25、3)
The reason is that the items are sorted as strings. (原因是项目按字符串排序。)
All the elements are converted to strings for comparisons. The lexicographic ordering is used for strings ( “3” > “25”). (所有元素都转换为字符串进行比较。词典顺序用于字符串( “3” > “25” )。)
For using your sorting order, you need to supply a function as the argument of the arr.sort(). (要使用排序顺序,您需要提供一个函数作为arr.sort ()的参数。)
Here is an example:
function compareNumeric(a, b) {
if (a > b) return 1;
if (a == b) return 0;
if (a < b) return -1;
}
let arr = [1, 3, 25];
arr.sort(compareNumeric);
console.log(arr); // 1, 3, 25
reverse
reverse (v.推翻 ;n.不幸)
This method is targeted at reversing the order of the elements in arr. (此方法旨在颠倒arr中元素的顺序。)
For example:
let arr = ["a", "b", "c", "d", "e"];
arr.reverse();
console.log(arr); // e,d,c,b,a
It can also return the array arr after reversing. (它还可以在反转后返回数组arr。)
split and join
split and join (拆分并加入)
The str.split(delim) method is used for splitting the string into an array by the particular delimiter delim. (Str.split (分隔符)方法用于通过特定分隔符分隔符将字符串拆分为数组。)
In the following example, it is split by a comma followed by space:
let animals = 'dog, cat, mouse';
let arr = animals.split(', ');
for (let animal of arr) {
console.log(`A message to ${animal}.`); // A message to dog (and other names)
}
By the way, this method has an alternative numeric argument that is a limit on the length of an array. In case it is provided, the extra elements will be ignored. Anyway, developers don’t use it often. (顺便说一句,此方法有一个替代的数值参数,它是对数组长度的限制。如果提供,多余的元素将被忽略。无论如何,开发人员不经常使用它。)
The example will look like this:
let arr = 'dog, cat, mouse, lion'.split(', ', 2);
console.log(arr); // dog, cat
If you want to reverse the split, call arr.join(glue). It will create an arr items string along with glue between them. Here is an example:
let animalsArr = ['dog', 'cat', 'mouse'];
let str = animalsArr.join(';'); // glue the array into a string using ;
console.log(str); // dog;cat;mouse
reduce/reduceRight
reduce/reduceRight
For iterating over an array, you can apply forEach, for, or for..of. (对于数组的迭代,您可以应用forEach、for或for.. of。)
In case you wish to iterate and return the data for each element, the map can be used. (如果您希望迭代并返回每个元素的数据,可以使用地图。)
The arr.reduce and arr.reduceRight methods do similar actions but are a bit more intricate. You can use it for calculating one value based on the array. (Arr.reduce和arr.reduceRight方法执行类似的操作,但更加复杂。您可以使用它来计算基于数组的一个值。)
The syntax is as follows:
let value = arr.reduce(function (accumulator, item, index, array) {
// ...
}, [initial]);
The arguments are:
the accumulator represents the result of the previous function call equaling initial the first time;
the item can be described as the current array item. (-项目可以被描述为当前数组项目。)
the index is its position. (-索引是它的位置。)
the array is the array. (-数组是数组。)
In this example, you can find a sum of an array in a single line:
let sumArr = [1, 2, 3, 4, 5];
let result = sumArr.reduce((sum, current) => sum + current, 0);
console.log(result); // 15
Array.isArray
Array.isArray
Arrays are based on objects. (数组基于对象。)
Hence, the typeof will not let you distinguish a plain object from an array:
console.log(typeof {}); // object
console.log(typeof []); // same
But developers use arrays so often that there exists a special method for doing it: Array.isArray(value). It returns true whenever the value is an array and false if not.
The example is the following:
console.log(Array.isArray({})); // false
console.log(Array.isArray([])); // true