The most comprehensive summary of array methods
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'];
Detect array
if(arr instanceof Array) {}
If the web page contains multiple frames, you need to use the following method to detect the array
if(Array.isArray(arr)) {}
arr.valueOf()
var colors = ['red', 'yellow']; colors.valueOf(); // > ['red', 'yellow']
arr.toString()
var colors = ['red', 'yellow']; colors.toString(); // > "red,yellow"
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
arr.pop()
Remove elements from the end of the array and return the deleted elements
var colors = ['red', 'yellow']; colors.pop(); // > 'yellow'
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
arr.shift ()
Delete elements from the head of the array and return the deleted elements
var colors = ['yellow', 'orange']; colors.shift(); // > 'yellow'
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]
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"]
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"]
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']
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"]
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"]
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"]
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]
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]
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
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
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
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
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 ]
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]
arr.forEach(fn)
遍历数组,没有返回值,fn的参数为
[ 调用every的数组的每一项元素 | 对应元素所在的位置 | 表示该数组 ]
numbers.forEach(function(item, index) { // do something })
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
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 });
跳过一次循环
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 ] 不会改变
$.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] // 原数组不受影响
$.inArray(item, array)
检测某一个元素item是否存在与数组之中,返回其所在的位置,如果不在,则返回-1
$.inArray(3, [1, 2, 3]); // > 2
$.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);
$.unique(arr)
过滤DOM数组中重复的元素
$.makeArray(obj)
将类数组对象转换为数组
$(elem).toArray()
将jQuery对象集合恢复成DOM数组
相关推荐:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file