Home > Web Front-end > JS Tutorial > body text

Summary of common array operation techniques in JavaScript

巴扎黑
Release: 2017-09-02 14:08:18
Original
1348 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!