Home Web Front-end JS Tutorial Summary of common array operation techniques in JavaScript

Summary of common array operation techniques in JavaScript

Sep 02, 2017 pm 02:08 PM
javascript js common

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();
Copy after login

Use push() to dynamically create a two-dimensional array instance<ul id = "source"><li>Beijing Air Quality:<b>90</b></li></ul>


##

var sourceList = document.querySelector(&#39;#source&#39;);
// 取得<ul>标签下所有<li>元素
var lis = sourceList.querySelectorAll(&#39;li&#39;);
// 取得<ul>标签下所有<b>元素
var bs = sourceList.querySelectorAll(&#39;li b&#39;);
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]);
}
Copy after login

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

is the city value.

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 elements

One-dimensional array

arr[subscript index]

Multi-dimensional array

arr [Outer array subscript][Inner element subscript]

length attribute

Add new item

arr[array.length] = []

Clear the array or clear

arr.length = 0 || (a value less than the number of items)

Judge that the array is not empty

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 result

It is recommended to use the forEach() method

Use 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]);
Copy after login

Application

##

data.forEach(function (item, index) {
 li = document.createElement(&#39;li&#39;);
 fragment.appendChild(li);
 li.innerHTML = &#39;第&#39; + digitToZhdigit(index + 1) + &#39;名:&#39; + item[0] + &#39;空气质量:&#39; + &#39;<b>&#39; + item[1] + &#39;</b>&#39;;
});
const numbers = [1, 2, 3, 4];
let sum = 0;
numbers.forEach(function(numer) {
 sum += number;
});
console.log(sum);
Copy after login

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
Copy after login

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 => {
});
Copy after login


Array sorting

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;
 }  
}
Copy after login

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;
}
Copy after login


Application examples

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(&#39;jack&#39;,20));
objectList.push(new Persion(&#39;tony&#39;,25));
objectList.push(new Persion(&#39;stone&#39;,26));
objectList.push(new Persion(&#39;mandy&#39;,23));
//按年龄从小到大排序
objectList.sort(function(a,b){
 return a.age-b.age
});
Copy after login

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); // 以表格输出到控制台,用于调试直观了然
Copy after login


reverse() method

Returns a reverse sorted array

var values = [1, 2, 3, 4, 5];
values.reverse();
alert(values); // 5,4,3,2,1
Copy after login

Others Array operation method function classification

Add array elements

arrayObj. push([item1 [item2 [. . . [itemN ]]]]); // 将一个或多个新元素添加到数组结尾,并返回数组新长度
arrayObj.unshift([item1 [item2 [. . . [itemN ]]]]); // 将一个或多个新元素添加到数组开始,数组中的元素自动后移,返回数组新长度
arrayObj.splice(insertPos,0,[item1[, item2[, . . . [,itemN]]]]); // 将一个或多个新元素插入到数组的指定位置,插入位置的元素自动后移,返回""。第二个参数不为0(要删除的项数)时则可以实现替换的效果。
arr[array.length] = [] // 使用length属性在数组末尾添加新项
Copy after login


Array Deletion of elements

##

arrayObj.pop(); // 移除末端一个元素并返回该元素值
arrayObj.shift(); // 移除前端一个元素并返回该元素值,数组中元素自动前移
arrayObj.splice(deletePos,deleteCount); // 删除从指定位置deletePos开始的指定数量deleteCount的元素,返回所移除的元素组成的新数组
Copy after login


Interception and merging of array elements

arrayObj.slice(startPos, [endPos]); // 以数组的形式返回数组的一部分,注意不包括 endPos 对应的元素,如果省略 endPos 将复制 startPos 之后的所有元素
arrayObj.concat([item1[, item2[, . . . [,itemN]]]]); // 将多个数组(也可以是字符串,或者是数组和字符串的混合)连接为一个数组,返回连接好的新的数组
Copy after login

数组的拷贝


arrayObj.slice(0); // 返回数组的拷贝数组,注意是一个新的数组,不是指向
arrayObj.concat(); // 返回数组的拷贝数组,注意是一个新的数组,不是指向
Copy after login

数组指定元素的索引(可以配合splice()使用)


arr.indexOf(searchElement[, fromIndex = 0]) // 返回首个被找到的元素(使用全等比较符===),在数组中的索引位置; 若没有找到则返回 -1。fromIndex决定开始查找的位置,可以省略。
lastIndexOf() // 与indexOf()一样,只不过是从末端开始寻找
Copy after login

数组的字符串化


arrayObj.join(separator); //返回字符串,这个字符串将数组的每一个元素值连接在一起,中间用 separator 隔开。
Copy after login

可以看做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
Copy after login

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

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 with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

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

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles