Summary of common array operation techniques in JavaScript
The following introduces array object traversal, reading, writing, sorting and other operations in JavaScript as well as string processing operations related to arrays. Friends who need it can refer to it
The effect diagram is as follows:
Tip: Right-click to open in a new tab to view a clear larger picture
The following introduces array object traversal, reading, writing, sorting and other operations in JavaScript as well as array-related operations String processing operations
Create array
Generally use array literal [] to create a new array, unless you want to create an array of a specified length
// good var arr = []; var arr = ['red', 'green', 'blue']; var arr = [ ['北京', 90], ['上海', 50], ['广州', 50] ]; // bad var arr = new Object();
Use push() to dynamically create a two-dimensional array instance<ul id="source"><li></ul>
Beijing Air Quality:<b>90</b>
##
var sourceList = document.querySelector('#source'); // 取得<ul>标签下所有<li>元素 var lis = sourceList.querySelectorAll('li'); // 取得<ul>标签下所有<b>元素 var bs = sourceList.querySelectorAll('li b'); var data = []; for (var i = 0, len = lis.length; i < len; i++) { // 法一:先对data添加一维空数组,使其成为二维数组后继续赋值 data.push([]); // 分割文本节点,提取城市名字 var newNod = lis[i].firstChild.splitText(2); data[i][0] = lis[i].firstChild.nodeValue; // 使用+转换数字 data[i][1] = +bs[i].innerHTML; // 法二:先对一维数组赋值,再添加到data数组中,使其成为二维数组 var li = lis[i]; var city = li.innerHTML.split("空气质量:")[0]; var num = +li.innerText.split("空气质量:")[1]; data.push([city,num]); }
String.prototype.split() Method is used to split a string into a string array. The split() method does not change the original string.
li.innerHTML.split("Air Quality:")-----The split array is the array of ["Beijing", "90"], and then take the array The first item of
Text.splitText()The method will split a text node into two text nodes. The original text node will contain the content from the beginning to the specified position, and the new text node will contain the remaining content. text below. This method will return a new text node
querySelector()The method receives a CSS selector and returns the first element matching the changed pattern. If it is not found, it returns null
querySelectorAll()The method accepts a CSS selector and returns a NodeList object, or empty if not found
Reading and setting
Accessing array elementsOne-dimensional arrayarr[subscript index]Multi-dimensional arrayarr [Outer array subscript][Inner element subscript]length attributeAdd new itemarr[array.length] = []
arr.length = 0 || (a value less than the number of items)
if(arr.length) {}
Array traversal
Traversing array is not used for in, because the array object may have attributes other than numbers, in this case for in will not get the correct resultIt is recommended to use the forEach() methodUse the traditional for loop
for(var i = 0, len = arr.length; i < len; i++){} for...in for (var index in arrayObj){ var obj = arrayObj[index]; } forEach() arr.forEach(function callback(currentValue, index, array) { //your iterator }[, thisArg]);
Application
##
data.forEach(function (item, index) { li = document.createElement('li'); fragment.appendChild(li); li.innerHTML = '第' + digitToZhdigit(index + 1) + '名:' + item[0] + '空气质量:' + '<b>' + item[1] + '</b>'; }); const numbers = [1, 2, 3, 4]; let sum = 0; numbers.forEach(function(numer) { sum += number; }); console.log(sum);
Extension 1: In ES6, you can Declare all local variables using let or const, without using the var keyword. Const is used by default unless the variable needs to be reassigned. const is used to declare constants, and let is a new way of declaring variables. It has a block-level scope that is enclosed by curly braces, so there is no need to consider the access issues of various nested variables.
var foo = true; if(foo) { let bar = foo*2; bar =something(bar); console.log(bar); } console.log(bar); // RefenceError
For details, see https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3. md
Extension 2: You can use arrow functions => to write shorter functions
MDN Arrow functions
numbers.forEach(numer => { });
sort() method
By default, the array item is transformed by calling the toString() method. Then compare the string order (ASCII code) and arrange the array from small to largeIn order to avoid similar numerical string comparisons, "10" will be ranked in front of "5", sort() accepts a comparison function compare() parameter, Compare by numerical size
function compare(a, b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } }
The return value of this function is less than 0, then a is ranked in front of b; if the return value is greater than 0, then b is ranked in front of a; if the return value Equal to 0, the relative positions of a and b remain unchanged. The final result is an ascending array. We can also produce descending sorted results by exchanging the values returned by the comparison function.
In addition, if the comparison is a number, the compare() function can be simplified as follows (a-b ascending order, b-a descending order)
function compare(a, b) { return a - b; }
You can sort a certain attribute of a specific object
var objectList = []; function Persion(name,age){ this.name=name; this.age=age; } objectList.push(new Persion('jack',20)); objectList.push(new Persion('tony',25)); objectList.push(new Persion('stone',26)); objectList.push(new Persion('mandy',23)); //按年龄从小到大排序 objectList.sort(function(a,b){ return a.age-b.age });
You can sort a certain column of a multi-dimensional array
var aqiData = [ ["北京", 90], ["上海", 50], ["福州", 10], ["广州", 50], ["成都", 90], ["西安", 100] ]; aqiData.sort(function (a, b) { return a[1] - b[1]; }); console.table(aqiData); // 以表格输出到控制台,用于调试直观了然
reverse() method
Returns a reverse sorted array
var values = [1, 2, 3, 4, 5]; values.reverse(); alert(values); // 5,4,3,2,1
Others Array operation method function classification
arrayObj. push([item1 [item2 [. . . [itemN ]]]]); // 将一个或多个新元素添加到数组结尾,并返回数组新长度 arrayObj.unshift([item1 [item2 [. . . [itemN ]]]]); // 将一个或多个新元素添加到数组开始,数组中的元素自动后移,返回数组新长度 arrayObj.splice(insertPos,0,[item1[, item2[, . . . [,itemN]]]]); // 将一个或多个新元素插入到数组的指定位置,插入位置的元素自动后移,返回""。第二个参数不为0(要删除的项数)时则可以实现替换的效果。 arr[array.length] = [] // 使用length属性在数组末尾添加新项
##
arrayObj.pop(); // 移除末端一个元素并返回该元素值 arrayObj.shift(); // 移除前端一个元素并返回该元素值,数组中元素自动前移 arrayObj.splice(deletePos,deleteCount); // 删除从指定位置deletePos开始的指定数量deleteCount的元素,返回所移除的元素组成的新数组
Interception and merging of array elements
arrayObj.slice(startPos, [endPos]); // 以数组的形式返回数组的一部分,注意不包括 endPos 对应的元素,如果省略 endPos 将复制 startPos 之后的所有元素 arrayObj.concat([item1[, item2[, . . . [,itemN]]]]); // 将多个数组(也可以是字符串,或者是数组和字符串的混合)连接为一个数组,返回连接好的新的数组
数组的拷贝
arrayObj.slice(0); // 返回数组的拷贝数组,注意是一个新的数组,不是指向 arrayObj.concat(); // 返回数组的拷贝数组,注意是一个新的数组,不是指向
数组指定元素的索引(可以配合splice()使用)
arr.indexOf(searchElement[, fromIndex = 0]) // 返回首个被找到的元素(使用全等比较符===),在数组中的索引位置; 若没有找到则返回 -1。fromIndex决定开始查找的位置,可以省略。 lastIndexOf() // 与indexOf()一样,只不过是从末端开始寻找
数组的字符串化
arrayObj.join(separator); //返回字符串,这个字符串将数组的每一个元素值连接在一起,中间用 separator 隔开。
可以看做split()的逆向操作
数组值求和
array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue)// 累加器和数组中的每个元素 (从左到右)应用一个函数,将其减少为单个值,返回函数累计处理的结果 var total = [0, 1, 2, 3].reduce(function(sum, value) { return sum + value; }, 0); // total is 6
The above is the detailed content of Summary of common array operation techniques in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

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.


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

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.

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version