Home > Article > Web Front-end > 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 instance1a87a7b28e610a00e612492f2af5b7df25edfb22a4f469ecb59f1190150159c6
Beijing Air Quality:a4b561c25d9afb9ac8dc4d70affff419900d36329ec37a2cc24d42c7229b69747abed06894275b65c1ab86501b08a632eb929d1f5ca49e04fdcb27f9465b944689
##
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);
var foo = true; if(foo) { let bar = foo*2; bar =something(bar); console.log(bar); } console.log(bar); // RefenceError
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!