Home > Web Front-end > JS Tutorial > body text

Summary of JavaScript array operation methods (with examples)

不言
Release: 2018-10-24 10:38:39
forward
1955 people have browsed it

This article brings you a summary of JavaScript array operation methods (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

ECMAScript provides many methods for manipulating items already contained in an array. Here I summarize my understanding of these methods. Among so many methods, I first used whether it will change the original array as the classification standard, and explain each method one by one.

1. The original array will not be changed

1. concat()

Usage method: array.concat(array2,array3,...,arrayX)
Return value: Returns a new array

concat() method is used to concatenate two or more arrays. This method does not modify the existing array, it only returns a copy of the concatenated array.
With no arguments passed, it simply copies the current array and returns the copy; if the values ​​passed are not arrays, the values ​​are simply added to the end of the resulting array.

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

console.log(arr1);  // [ 1, 2, 3 ]
console.log(arr2);  // [ 1, 2, 3, 4, 5, 6 ]
Copy after login

2. join()

Usage method: array.join(separator)
Return value: Returns a string

join() method is used to All elements in the array are put into a string. Elements are separated by the specified delimiter. By default, ',' is used to separate the elements, which does not change the original array.

var arr1 = [1,2,3];
var arr2 = arr1.join();

console.log(arr1);  // [ 1, 2, 3 ]
console.log(arr2);  // 1,2,3
Copy after login
has come across a function before that requires the generation of multiple consecutive *. At first, it can be done directly using a for loop. Later, after learning about the join() method, I found that it can be done in one sentence.
var arr3 = "";
for(let i = 0; i < 15; i ++) {
    arr3 = arr3 + "*";
}
console.log(arr3);  // ***************

var arr4 = new Array(16).join("*");
console.log(arr4);  // ***************
Copy after login

3. slice()

Usage method: array.slice(start, end)
Return value: Returns a new array, including from start to end (excluding this element) Elements in arrayObject

slice() accepts one or two parameters, which are the starting and ending positions of the items to be returned.
With only one parameter, the slice() method returns all items from the position specified by the parameter to the end of the current array;
If there are two parameters, the method returns the items between the start and end positions. --but does not include items at the end position.
If the parameter is a negative number, it specifies the position starting from the end of the array. That is, -1 refers to the last element, -2 refers to the second to last element, and so on.

var arr1 = [1,2,3,4,5,6];
var arr2 = arr1.slice(1);
var arr3 = arr1.slice(2,4);
var arr4 = arr1.slice(-4,-2);  // 等价于 arr1.slice(2,4);

console.log(arr1);  // [ 1, 2, 3, 4, 5, 6 ]
console.log(arr2);  // [ 2, 3, 4, 5, 6 ]
console.log(arr3);  // [ 3, 4 ]
console.log(arr4);  // [ 3, 4 ]
Copy after login
uses this method to convert pseudo arrays into standard data
    Array.prototype.slice.call(arguments)
Copy after login

4. some()

Usage method: array.some(function(currentValue,index,arr),thisValue)
Return value: Boolean value

or ==> some() runs the given function on each item in the array. If the function returns true for any item, the remaining elements will not be Performs a test; if no element satisfies the condition, returns false.

function compare(item, index, arr){
    return item > 10;
}

[2, 5, 8, 1, 4].some(compare);  // false
[20, 5, 8, 1, 4].some(compare);  // true
Copy after login

5. every()

Usage method: array.every(function(currentValue,index,arr),thisValue)
Return value: Boolean value

and ==> every() runs the given function on each item in the array. If the function returns true for each item, the remaining elements will not be tested; if there is an element that does not meet the condition, Returns false.

function compare(item, index, arr){
    return item > 10;
}

[20, 50, 80, 11, 40].every(compare);  // true
[20, 50, 80, 10, 40].every(compare);  // false
Copy after login

5. filter()

Usage method: array.filter(function(currentValue,index,arr), thisValue)
Return value: Return array

The filter() method creates a new array, and the elements in the new array are checked for all elements in the specified array that meet the conditions.
Run the given function on each item of the array and return an array composed of items whose result is true.

function filterArr(item, index, arr){
    return item > 4;
}

[2, 5, 8, 1, 4].filter(filterArr);  // [5,8]
Copy after login

6. map()

Usage method: array.map(function(currentValue,index,arr), thisValue)
Return value: Return array

The map() method returns a new array, and the elements in the array are the values ​​of the original array elements after calling the function.

function mapArr(item, index, arr){
    return item * 4;
}

[2, 5, 8, 1, 4].map(mapArr);  // [8,20,32,4,16]
Copy after login
A question that is often asked in written examinations and interviews is to implement a map array method. The following is a method I wrote myself
var arr = [2, 4, 8, 6, 1];

Array.prototype.myMap = function (fn, thisValue) {
    var arr = this,
        len = arr.length,
        tmp = 0,
        result = [];
    thisValue = thisValue || null;
    for (var i = 0; i < len; i++) {
        var item = arr[i],
            index = i;
        tmp = fn.call(thisValue, item, index, arr);
        result.push(tmp);
    }
    return result
}

function mapArr(item, index, arr) {
    return item * 4;
}
arr.myMap(mapArr)   // [8, 16, 32, 24, 4]
Copy after login

6. forEach()

Usage: array.forEach(function(currentValue, index, arr), thisValue)
Return value: undefined

forEach() method is used to call each element of the array and pass the element to Callback. This method has no return value.
Essentially the same as using a for loop to iterate over an array.

var items = [1, 2, 4, 7, 3];
var copy = [];

items.forEach(function(item,index){
  copy.push(item*index);
})

console.log(items);  // [ 1, 2, 4, 7, 3 ]
console.log(copy);  // [ 0, 2, 8, 21, 12 ]
Copy after login

7. reduce() and reduceRight()

Usage method: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Return value: Return calculation Result

Required. Function used to execute each array element. Optional. Initial value passed to the function

函数参数

Parameter Description
##function(total,currentValue , index,arr)
initialValue
参数 描述
total 必需。初始值, 或者计算结束后的返回值。
currentValue 必需。当前元素
currentIndex 可选。当前元素的索引
arr 可选。当前元素所属的数组对象。

这两个方法都会迭代数组的所有项,然后构建一个最终返回的值。其中,reduce()方法中数组的第一项开始,逐个遍历到最后;而reduceRight()则从数组的最后一项开始,向前遍历到第一项。

如果没有设置initialValue,total的值为数组第一项,currentValue为数组第二项。
如果设置了initialValue,则total的值就是initialValue,currentValue为数组第一项。

var numbers = [65, 44, 12, 4];
 
function getSum(total,currentValue, index,arr) {
    return total + currentValue;
}

var res = numbers.reduce(getSum);

console.log(numbers);  // [ 65, 44, 12, 4 ]
console.log(res);  //  125

var numbers = [65, 44, 12, 4];
 
function getSum(total,currentValue, index,arr) {
    return total + currentValue;
}

var res = numbers.reduce(getSum, 10);  // 初始值设置为10,所以最终结果也相应的加10

console.log(res);  //  135
Copy after login
具体reduce()方法用得好是能起到很大的作用的,对于批量修改从后台获取的数据十分有用,可以参考JS进阶篇--JS数组reduce()方法详解及高级技巧

二、会改变原数组

1. push()

使用方法:array.push(item1, item2, ..., itemX)
返回值: 返回新数组的长度

push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。

var arr= [65, 44, 12, 4];
var arr1 = arr.push(2,5);

console.log(arr); // [ 65, 44, 12, 4, 2, 5 ]
console.log(arr1); // 6
Copy after login

2. pop()

使用方法:array.pop()
返回值: 数组原来的最后一个元素的值(移除的元素)

pop()方法用于删除并返回数组的最后一个元素。返回最后一个元素,会改变原数组。

var arr = [65, 44, 12, 4];
var arr1 = arr.pop();

console.log(arr); // [ 65, 44, 12 ]
console.log(arr1); //  4
Copy after login

3. unshift()

使用方法:array.unshift(item1,item2, ..., itemX)
返回值: 返回新数组的长度

unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。返回新长度,改变原数组。

var arr = [65, 44, 12, 4];
var arr1 = arr.unshift(1);

console.log(arr); // [ 1, 65, 44, 12, 4 ]
console.log(arr1); //  5
Copy after login

4. shift()

使用方法:array.shift()
返回值: 数组原来的第一个元素的值(移除的元素)

shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。返回第一个元素,改变原数组。

var arr = [65, 44, 12, 4];
var arr1 = arr.shift();

console.log(arr); // [ 44, 12, 4 ]
console.log(arr1); //   65
Copy after login

5. sort()

使用方法:array.sort(sortfunction)
返回值: 返回排序后的数组(默认升序)

sort() 法用于对数组的元素进行排序。
排序顺序可以是字母或数字,并按升序或降序。
默认排序顺序为按字母升序。

P.S 由于排序是按照 Unicode code 位置排序,所以在排序数字的时候,会出现"10"在"5"的前面,所以使用数字排序,你必须通过一个函数作为参数来调用。

var values = [0, 1, 5, 10, 15];
values.sort();
console.log(values);  // [ 0, 1, 10, 15, 5 ]

values.sort(function(a, b){
  return a - b;
})
console.log(values);  //  [0, 1, 5, 10, 15 ]
Copy after login

6. reverse()

使用方法:array.reverse()
返回值: 返回颠倒后的数组

reverse() 方法用于颠倒数组中元素的顺序。返回的是颠倒后的数组,会改变原数组。

var values = [0, 1, 5, 10, 15];
values.reverse();
console.log(values);  // [ 15, 10, 5, 1, 0 ]
Copy after login

7. fill()

使用方法:array.fill(value, start, end)
返回值: 返回新的被替换的数组

fill()方法用于将一个固定值替换数组的元素。

参数 描述
value 必需。填充的值。
start 可选。开始填充位置。
end 可选。停止填充位置(不包含) (默认为 array.length)
var values = [0, 1, 5, 10, 15];
values.fill(2);
console.log(values);  // [ 2, 2, 2, 2, 2 ]

values = [0, 1, 5, 10, 15];
values.fill(2,3,4);
console.log(values);  // [ 0, 1, 5, 2, 15 ]
Copy after login

8. splice()

使用方法:array.splice(index,howmany,item1,.....,itemX)

返回值: 如果从 arrayObject 中删除了元素,则返回的是含有被删除的元素的数组

splice()有多种用法:

1、删除: 可以删除任意数量的项,只需要指定2个参数:要删除的第一项的位置和要删除的项数。splice(0,2) // 会删除数组中前两项

2、插入: 可以向指定位置插入任意数量的项,只需提供3个参数:起始位置、0(要删除的项数)和要插入的项。如果要插入多个项,可以再传入第四、第五,以至任意多个项。splice(2,0,1,4) // 会从数组位置2的地方插入1和4

3、替换: 可以向指定位置插入任意数量的项,且同时删除任意数量的项,只需提供3个参数:起始位置、要删除的项数和要插入的项。插入的项不必与删除的项数相等。splice(2,3,1,4) // 会从数组位置2删除两项,然后再从位置2的地方插入1和4

// 删除
var values = [4,8,0,3,7];
var remove = values.splice(3,1);
console.log(values);  // [ 4, 8, 0, 7 ]
console.log(remove);  // [ 3 ]    删除第四项
// 插入
remove = values.splice(2,0,1,2);
console.log(values);  // [ 4, 8, 1, 2, 0, 7 ]
console.log(remove);  // []  从位置2开始插入两项,由于没有删除所有返回空函数
// 替换
remove = values.splice(2,2,6,9,10);
console.log(values);  // [ 4, 8, 6, 9, 10, 0, 7 ]
console.log(remove);  // [ 1, 2 ]  从位置2开始删除两项,同时插入三项
Copy after login

The above is the detailed content of Summary of JavaScript array operation methods (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template