Home > headlines > body text

The most comprehensive summary of array methods

小云云
Release: 2017-12-13 15:35:11
Original
2019 people have browsed it

The so-called array is an unordered sequence of elements. If a limited collection of variables of the same type is named, then the name is the array name. The individual variables that make up an array are called components of the array, also called elements of the array, and sometimes called subscript variables. The numeric number used to distinguish the individual elements of an array is called a subscript. In programming, an array is a form of organizing several elements of the same type in an unordered manner for the convenience of processing. These unordered collections of similar data elements are called arrays. In this article, we mainly share with you the most complete summary of array methods. We will use native javascript methods, hoping to help everyone.

Create array
var colors = [];
var colors = ['red', 'blue'];
Copy after login
Detect array
if(arr instanceof Array) {}
Copy after login

If the web page contains multiple frames, you need to use the following method to detect the array

if(Array.isArray(arr)) {}
Copy after login
arr.valueOf()
var colors = ['red', 'yellow'];
colors.valueOf();
// > ['red', 'yellow']
Copy after login
arr.toString()
var colors = ['red', 'yellow'];
colors.toString();
// > "red,yellow"
Copy after login
arr.push(item)

Add elements from the end of the array and return the length of the new array

var colors = ['red', 'yellow'];
colors.push('pink');
// > 3
Copy after login
arr.pop()

Remove elements from the end of the array and return the deleted elements

var colors = ['red', 'yellow'];
colors.pop();
// > 'yellow'
Copy after login
arr.unshift(item)

Add elements from the head of the array and return the length of the new array

var colors = ['green', 'pink'];
colors.unshift('pink');
// > 3
Copy after login
arr.shift ()

Delete elements from the head of the array and return the deleted elements

var colors = ['yellow', 'orange'];
colors.shift();
// > 'yellow'
Copy after login
arr.reverse()

Reverse The order of the array, and returns the reordered array, the original array will be changed

[1, 2, 3, 'reer', 'game', 2, 5].reverse();
// > [5, 2, "game", "reer", 3, 2, 1]
Copy after login
arr.sort(fn)

If no parameters are passed, by default The elements in the array will be converted to strings for comparison, so it is generally not recommended to directly use the default arr.sort() for sorting.
The return value is the new array after sorting. The original array will be changed

  • Sort the numerical elements in the array from small to large.

var demo = [1, 4, 2, 'reee', 'name', '9', 'doc'];
demo.sort(function(a, b)) {
    return a - b;
}
// > [1, 2, 4, "reee", "name", "9", "doc"]
Copy after login
  • Sort the numerical elements in the array from large to small

var demo = [1, 4, 2, 'reee', 'name', '9', 'doc'];
demo.sort(function(a, b) {
    return b - a;
})
// > [4, 2, 1, "reee", "name", "9", "doc"]
Copy after login
arr.concat(otherArr )

If you pass an element or array into the parameter, the parameter will be merged into arr and the new merged array will be returned. The original array will not change

var arr = [1, 3, 'jake'];
arr.concat('rose', [2, 'fi']);
// > [1, 3, 'jake', 'rose', 2, 'fi']
Copy after login
arr .slice()

Cut the array and return the array after cutting. The elements will not change

  • Pass in a parameter indicating the starting position. The end position is the end

var arr = [4, 2, 1, "reee", "name", "9", "doc"];
arr.slice(2);
// > [1, "reee", "name", "9", "doc"]
Copy after login
  • Pass in 2 parameters, indicating the starting position and the end position, but not including the element where the end position is located

var arr = [4, 2, 1, "reee", "name", "9", "doc"];
arr.slice(2, 4);
// > [1, "reee"]
Copy after login
arr.splice()

Depending on the parameters, you can delete, insert, and replace elements respectively, which will change the original array

  • Delete

# Pass in 2 parameters, indicating the starting position and the number of elements to be deleted, and return the deleted Array composed of dropped elements

var arr = [4, 2, 1, "reee", "name", "9", "doc"];
arr.splice(2, 3);
// > [1, "reee", "name"]
// arr: [4, 2, 1, "9", "doc"]
Copy after login
  • Insert

Pass in 3 parameters, [Starting position | The number of deleted items is 0 | elements to be inserted], and finally returns an array of deleted elements. Because the number of deleted items here is 0, an empty array will be returned

var arr = [2, 4, 6];
arr.splice(2, 0, 'red', 'green'); 
// > []
// arr: [2, 4, "red", "green", 6]
Copy after login
  • Replace

#Pass in three parameters, [starting position | number of items to be deleted is 1 | element to be inserted], and finally return the deleted element The array composed of

var arr = [2, 4, 9];
arr.splice(1, 1, ['tim', 'tom']);
// > [4]
// arr: [2, ['tim', 'tom'], 9]
Copy after login
  • Summary Therefore, this method will achieve different functions due to different parameters. All parameters from beginning to end are

[Starting position | The number of elements to be deleted | The value of the element to be inserted, multiple values ​​can be written]

arr.indexOf(item)

Verify whether the array contains an element and return the position of the first matching element in the array. If not, return -1

var arr = [2, 'tim', 4, 5, 2];
arr.indexOf('tim');
// > 1
arr.indexOf('jake');
// > -1
Copy after login
arr. lastIndexOf(item)

Verifies whether the array contains an element, but starts the search from the end of the array and returns the position of the first matching element. If not, returns -1

var arr = [2, 'tim', 4, 5, 2];
arr.lastIndexOf('tim');
// > 1
arr.indexOf('jake');
// > -1
Copy after login

IE6, 7, 8 do not support the indexOf and lastIndexOf methods

arr.every()

Runs the given function on each item and returns true if the function returns true for each item. There will be a function as a parameter of every. This function also has 3 parameters, which are
[Each element of the array that calls every|The position of the corresponding element|Represents the array]

var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var everyRes = numbers.every(function(item, index, array) {
    return item > 2;
})
// > false
Copy after login
arr.some()

Run the given function on each item in the array, returning true if the function returns true for one of the items. There will be a function as a parameter of every. This function also has 3 parameters, which are
[Each element of the array that calls every|The position of the corresponding element|Represents the array]

var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var everyRes = numbers.some(function(item, index, array) {
    return item > 2;
})
// > true
Copy after login
arr.filter(fn)

Filter method. Returns an array consisting of elements that meet the condition. The parameters of fn are
[Each element of the array calling every | The position of the corresponding element | Represents the array]

var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var everyRes = numbers.filter(function(item, index, array) {
    return item > 2;
})
// > [ 3, 4, 5, 4, 3 ]
Copy after login
arr.map(fn)

对数组的每一项进行计算等处理,返回处理结果组成的数组,fn的参数为
[ 调用every的数组的每一项元素 | 对应元素所在的位置 | 表示该数组 ]

var numbers = [1, 2, 3, 3, 2, 1];
var everyRes = numbers.map(function(item, index, array) {
    return item > 2;
})
// >[false, false, true, true, false, false]
Copy after login
arr.forEach(fn)

遍历数组,没有返回值,fn的参数为
[ 调用every的数组的每一项元素 | 对应元素所在的位置 | 表示该数组 ]

numbers.forEach(function(item, index) {
    // do something
})
Copy after login
arr.reduce(fn)

缩减方法。fn的参数为
[ 前一个元素 | 当前元素,从1开始 | 后一个元素的序列,从1开始计数 | 表示该数组 ]

var values = [1, 2, 3, 4, 5];
var sum = values.reduce(function(prev, cur, index, array) {
    return prev + cur;
})
// > 15 
//每一次迭代之后的结果分别为
// [3, 3, 4, 5]
// [6, 4, 5]
// [10, 5]
// 15
Copy after login
arr.reduceRight(fn)

与reduce一模一样,只是方向相反。

jQuery相关方法

$.each(arr, fn)

遍历数组或者对象,fn有2个参数,分别为, 比原生的for in 更加健壮
[ 数组的索引或者对象的key值 | 索引或者key值对应的value值 ]

var arr = [1, 2, 3];
$.each(arr, function(key, value) {
    // do something
});
Copy after login
  • 跳过一次循环 return | return true

  • 终止循环 return false

$.grep(arr, fn)

过滤方法,功能类同原生中的arr.filter(fn)。此处fn的参数如下
[ value: 对象/数组的值 | key值或者序列 ]

var arr = [ 1, 3, 6, 4 ];
$.grep(arr, function(val, key) {
    return val >= 3;
});
// > [3, 6, 4]
// arr : [ 1, 3, 6, 4 ] 不会改变
Copy after login
$.map(arr, fn)

对每项进行处理,返回处理结果组成的数组,此处fn的参数如下
[ value: 对象/数组的值 | key值或者序列 ]

var arr = [1, 2, 5, 3];
$.map(arr, function(val, key) {
    return val * 10;
})
// > [10, 30, 30, 20, 10]
// 原数组不受影响
Copy after login
$.inArray(item, array)

检测某一个元素item是否存在与数组之中,返回其所在的位置,如果不在,则返回-1

$.inArray(3, [1, 2, 3]);
// > 2
Copy after login
$.merge(arr1, arr2)

合并数组,会改变第一个参数的数组为合并之后的数组,返回合并之后的数组

var arr = [1, 3, 4];
var arr2 = [4, 3, 1];
$.merge(arr, arr2);
// > [1, 3, 4, 4, 3, 1]
// 为了防止第一个数组被改变,可以使用下面的方式来写
$.merge($.merge([], arr), arr2);
Copy after login
$.unique(arr)

过滤DOM数组中重复的元素

$.makeArray(obj)

将类数组对象转换为数组

$(elem).toArray()

将jQuery对象集合恢复成DOM数组

相关推荐:

最实用的JS数组函数整理

PHP常用数组(Array)函数总结整理

PHP 数组排序方法总结

几种PHP数组定义的方法

JavaScript如何创建数组?

Related labels:
js
source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!