What this article brings to you is a summary (code) of common array operation methods in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. concat()
The concat() method is used to connect two or more arrays. This method does not modify the existing array, it only returns a copy of the concatenated array.
var arr1 = [1,2,3]; var arr2 = [4,5]; var arr3 = arr1.concat(arr2); console.log(arr1);//[1, 2, 3] console.log(arr3);//[1, 2, 3, 4, 5]
2. join()
The join() method is used to put all elements in the array 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 arr = [2,3,4]; console.log(arr.join());//2,3,4 console.log(arr);//[2, 3, 4]
3. push()
push() method can add one or more elements to the end of the array and return the new length. Adding at the end returns the length, which will change the original array.
var a = [2,3,4]; var b = a.push(5); console.log(a); //[2,3,4,5] console.log(b);//4 push方法可以一次添加多个元素push(data1,data2....)
4. pop()
The pop() method is used to delete and return the last element of the array. Returning the last element will change the original array.
var arr = [2,3,4]; console.log(arr.pop());//4 console.log(arr); //[2,3]
5. shift()
The shift() method is used to delete the first element of the array and return the value of the first element. Returns the first element, changing the original array.
var arr = [2,3,4]; console.log(arr.shift()); //2 console.log(arr); //[3,4]
6. unshift()
The unshift() method can add one or more elements to the beginning of the array and return the new length. Returns the new length, changing the original array.
var arr = [2,3,4,5]; console.log(arr.unshift(3,6)); //6 console.log(arr); //[3, 6, 2, 3, 4, 5]
7. slice()
Returns a new array containing the elements in arrayObject from start to end (excluding this element). Returns the selected element. This method does not modify the original array.
var arr = [2,3,4,5]; console.log(arr.slice(1,3)); //[3,4] console.log(arr); //[2,3,4,5]
8. splice()
The splice() method can delete zero or more elements starting from index and replace them with one or more values declared in the parameter list elements that were removed. If an element is deleted from arrayObject, an array containing the deleted element is returned. The splice() method directly modifies the array.
var a = [5,6,7,8]; console.log(a.splice(1,0,9)); //[] console.log(a); // [5, 9, 6, 7, 8] var b = [5,6,7,8]; console.log(b.splice(1,2,3)); //[6, 7] console.log(b); //[5, 3, 8]
9. substring() and substr()
Same point: if you just write one parameter:
substr(startIndex);
substring(startIndex);
Both have the same function: they intercept the string fragment from the current subscript to the end of the string.
var str = '123456789'; console.log(str.substr(2)); // "3456789" console.log(str.substring(2));// "3456789"
Difference: The second parameter
substr(startIndex,lenth): The second parameter is to intercept the length of the string (intercept a string of a certain length from the starting point)
substring (startIndex, endIndex): The second parameter is to intercept the final subscript of the string (intercept the string between the two positions, 'including the head but not the tail')console.log("123456789".substr(2,5)); // "34567" console.log("123456789".substring(2,5));// "345"
10. sort Sorting
Sort by Unicode code position, default ascending order:
- var fruit = ['cherries', 'apples', 'bananas'];
- fruit.sort(); // ['apples', 'bananas', 'cherries']
var scores = [1, 10, 21, 2]; scores.sort(); // [1, 10, 2, 21]
11. reverse()
reverse() method is used to reverse the order of elements in the array. What is returned is the reversed array, which will change the original array.
var arr = [2,3,4]; console.log(arr.reverse()); //[4, 3, 2] console.log(arr); //[4, 3, 2]
Twelve, indexOf and lastIndexOf
both accept two parameters: the value to be searched and the starting position to search.
If it does not exist, return -1; if it exists, return the position. indexOf searches from front to back, and lastIndexOf searches from back to front.
indexOf: var a = [2, 9, 9]; a.indexOf(2); // 0 a.indexOf(7); // -1 if (a.indexOf(7) === -1) { // element doesn't exist in array } lastIndexOf: var numbers = [2, 5, 9, 2]; numbers.lastIndexOf(2); // 3 numbers.lastIndexOf(7); // -1 numbers.lastIndexOf(2, 3); // 3 numbers.lastIndexOf(2, 2); // 0 numbers.lastIndexOf(2, -2); // 0 numbers.lastIndexOf(2, -1); // 3
13. every
Run the given function on each item of the array, and return true if each item returns ture.
function isBigEnough(element, index, array) { return element <p>14. some<br>Run the given function on each item of the array. If any item returns ture, it returns true. </p><pre class="brush:php;toolbar:false">function compare(element, index, array) { return element > 10; } [2, 5, 8, 1, 4].some(compare); // false [12, 5, 8, 1, 4].some(compare); // true
15. filter
Run the given function on each item of the array and return an array composed of items whose result is true.
var words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"]; var longWords = words.filter(function(word){ return word.length > 6; }); // Filtered array longWords is ["exuberant", "destruction", "present"]
16. map
Run the given function on each item of the array and return the result of each function call to form a new array.
var numbers = [1, 5, 10, 15]; var doubles = numbers.map(function(x) { return x * 2; }); // doubles is now [2, 10, 20, 30] // numbers is still [1, 5, 10, 15]
17. forEach array traversal
const items = ['item1', 'item2', 'item3']; const copy = []; items.forEach(function(item){ copy.push(item) });
18. reduce
reduce executes the callback function for each element in the array in sequence, excluding those that are deleted or have never been deleted from the array The assigned element accepts four parameters: the initial value (or the return value of the last callback function), the current element value, the current index, and the array in which reduce is called.
无初始值: var arr = [1, 2, 3, 4]; var sum = arr.reduce(function(prev, cur, index, arr) { console.log(prev, cur, index); return prev + cur; }) console.log(arr, sum);
Print results:
1 2 1
3 3 2
6 4 3
[1, 2, 3, 4] 10
You can see it here In the above example, the index starts from 1, and the value of the first prev is the first value of the array. The array length is 4, but the reduce function loops 3 times.
Has initial value:
var arr = [1, 2, 3, 4]; var sum = arr.reduce(function(prev, cur, index, arr) { console.log(prev, cur, index); return prev + cur; },0) //注意这里设置了初始值 console.log(arr, sum);
Print result:
0 1 0
1 2 1
3 3 2
6 4 3
[1, 2, 3 , 4] 10
In this example, the index starts from 0, the first prev value is the initial value 0 we set, the array length is 4, and the reduce function loops 4 times.
Conclusion: If no initialValue is provided, reduce will execute the callback method starting from index 1, skipping the first index. If initialValue is provided, starts at index 0.
ES6 adds new methods for operating arrays
1. find()
Pass in a callback function, find the first element in the array that meets the current search rules, return it, and terminate the search.
const arr = [1, "2", 3, 3, "2"] console.log(arr.find(n => typeof n === "number")) // 1
2. findIndex()
Pass in a callback function, find the first element in the array that meets the current search rules, return its subscript, and terminate the search.
const arr = [1, "2", 3, 3, "2"] console.log(arr.findIndex(n => typeof n === "number")) // 0
3. fill()
Replace the elements in the array with new elements, and you can specify the replacement subscript range.
arr.fill(value, start, end)
4、copyWithin()
选择数组的某个下标,从该位置开始复制数组元素,默认从0开始复制。也可以指定要复制的元素范围。
arr.copyWithin(target, start, end) const arr = [1, 2, 3, 4, 5] console.log(arr.copyWithin(3)) // [1,2,3,1,2] 从下标为3的元素开始,复制数组,所以4, 5被替换成1, 2 const arr1 = [1, 2, 3, 4, 5] console.log(arr1.copyWithin(3, 1)) // [1,2,3,2,3] 从下标为3的元素开始,复制数组,指定复制的第一个元素下标为1,所以4, 5被替换成2, 3 const arr2 = [1, 2, 3, 4, 5] console.log(arr2.copyWithin(3, 1, 2)) // [1,2,3,2,5] 从下标为3的元素开始,复制数组,指定复制的第一个元素下标为1,结束位置为2,所以4被替换成2
5、from
将类似数组的对象(array-like object)和可遍历(iterable)的对象转为真正的数组。
const bar = ["a", "b", "c"]; Array.from(bar); // ["a", "b", "c"] Array.from('foo'); // ["f", "o", "o"]
6、of
用于将一组值,转换为数组。这个方法的主要目的,是弥补数组构造函数 Array() 的不足。因为参数个数的不同,会导致 Array() 的行为有差异。
Array() // [] Array(3) // [, , ,] Array(3, 11, 8)// [3, 11, 8] Array.of(7); // [7] Array.of(1, 2, 3); // [1, 2, 3] Array(7);// [ , , , , , , ] Array(1, 2, 3); // [1, 2, 3]
7、entries() 返回迭代器:返回键值对
//数组 const arr = ['a', 'b', 'c']; for(let v of arr.entries()) { console.log(v) } // [0, 'a'] [1, 'b'] [2, 'c'] //Set const arr = new Set(['a', 'b', 'c']); for(let v of arr.entries()) { console.log(v) } // ['a', 'a'] ['b', 'b'] ['c', 'c'] //Map const arr = new Map(); arr.set('a', 'a'); arr.set('b', 'b'); for(let v of arr.entries()) { console.log(v) } // ['a', 'a'] ['b', 'b']
8、values() 返回迭代器:返回键值对的value
//数组 const arr = ['a', 'b', 'c']; for(let v of arr.values()) { console.log(v) } //'a' 'b' 'c' //Set const arr = new Set(['a', 'b', 'c']); for(let v of arr.values()) { console.log(v) } // 'a' 'b' 'c' //Map const arr = new Map(); arr.set('a', 'a'); arr.set('b', 'b'); for(let v of arr.values()) { console.log(v) } // 'a' 'b'
9、keys() 返回迭代器:返回键值对的key
//数组 const arr = ['a', 'b', 'c']; for(let v of arr.keys()) { console.log(v) } // 0 1 2 //Set const arr = new Set(['a', 'b', 'c']); for(let v of arr.keys()) { console.log(v) } // 'a' 'b' 'c' //Map const arr = new Map(); arr.set('a', 'a'); arr.set('b', 'b'); for(let v of arr.keys()) { console.log(v) } // 'a' 'b'
10、includes
判断数组中是否存在该元素,参数:查找的值、起始位置,可以替换 ES5 时代的 indexOf 判断方式。indexOf 判断元素是否为 NaN,会判断错误。
var a = [1, 2, 3]; a.includes(2); // true a.includes(4); // false
【相关推荐:JavaScript视频教程】
The above is the detailed content of Summary of common array operation methods in JavaScript (code). For more information, please follow other related articles on the PHP Chinese website!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.