Summary of JavaScript array operation methods (with examples)
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 ]
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,3has 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 <h3 id="slice">3. slice()</h3><p>Usage method: array.slice(start, end)<br>Return value: Returns a new array, including from start to end (excluding this element) Elements in arrayObject</p><p>slice() accepts one or two parameters, which are the starting and ending positions of the items to be returned. <br>With only one parameter, the slice() method returns all items from the position specified by the parameter to the end of the current array; <br>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. <br>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. </p><pre class="brush:php;toolbar:false">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 ]uses this method to convert pseudo arrays into standard data
Array.prototype.slice.call(arguments)
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
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
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]
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]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 myselfvar 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 <h3 id="forEach">6. forEach()</h3><p>Usage: array.forEach(function(currentValue, index, arr), thisValue)<br>Return value: undefined</p><p>forEach() method is used to call each element of the array and pass the element to Callback. This method has no return value. <br>Essentially the same as using a for loop to iterate over an array. </p><pre class="brush:php;toolbar:false">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 ]
7. reduce() and reduceRight()
Usage method: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Return value: Return calculation Result
Parameter | Description |
---|---|
##function(total,currentValue , index,arr)
| Required. Function used to execute each array element. |
initialValue
| Optional. Initial value passed to the function
参数 | 描述 |
---|---|
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具体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
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
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
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
5. sort()
使用方法:array.sort(sortfunction)
返回值: 返回排序后的数组(默认升序)
排序顺序可以是字母或数字,并按升序或降序。
默认排序顺序为按字母升序。
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 ]
6. reverse()
使用方法:array.reverse()
返回值: 返回颠倒后的数组
reverse() 方法用于颠倒数组中元素的顺序。返回的是颠倒后的数组,会改变原数组。
var values = [0, 1, 5, 10, 15]; values.reverse(); console.log(values); // [ 15, 10, 5, 1, 0 ]
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 ]
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开始删除两项,同时插入三项
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!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment
