Common Array Operations and JavaScript operations in javascript

Source: Internet
Author: User

Common Array Operations and JavaScript operations in javascript

As follows:

Tip: Right-click to open the new tab.

The following describes the operations of array object traversal, reading/writing, sorting, and array-related string processing in JavaScript.

Create an array

Generally, [] is used to create a new array, unless you want to create an array of the specified length

// Goodvar arr = []; var arr = ['red', 'green', 'blue']; var arr = [['beijing', 90], ['shanghai', 50], ['guangzhou ', 50]; // bad var arr = new Object ();

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 ('# source'); // obtain all <li> element var lis = sourceList under the <ul> label. querySelectorAll ('lil'); // obtain all <B> element var bs = sourceList under the <ul> label. querySelectorAll ('Li B '); var data = []; for (var I = 0, len = lis. length; I <len; I ++) {// Method 1: First add a one-dimensional empty array to the data, make it a two-dimensional array, and then assign a value to data. push ([]); // split the text node and extract the city name var newNod = lis [I]. firstChild. splitText (2); data [I] [0] = lis [I]. firstChild. nodeValue; // use + to convert data [I] [1] = + bs [I]. innerHTML; // Method 2: assign values to one-dimensional arrays and add them to the data array to make them a two-dimensional array var li = lis [I]; var city = li. innerHTML. split ("Air Quality:") [0]; var num = + li. innerText. split ("Air Quality:") [1]; data. push ([city, num]);}

String.prototype.split() The 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 an array of ["Beijing", "90"], and then an array is obtained.

The first item, that is, the city value.

Text.splitText()The method divides a text node into two text nodes. The original text node will contain the content from the start to the specified position, and the new text node will contain the remaining text. This method returns a new text node.

querySelector()Method receives a CSS selector and returns the first element that matches the pattern change. If no element is found, null is returned.

querySelectorAll()The method accepts a CSS selector and returns a NodeList object. If not found, it is null.

Read and set

Access 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 array or clear

Arr. length = 0 | (less than the number of items)

Judge whether the array is not empty

if(arr.length) {}

Array Traversal

The for in clause is not used for Array traversal, because the array object may have attributes other than numbers. in this case, the for in clause will not get the correct result.

The forEach () method is recommended.

Use traditional for Loop

for(var i = 0, len = arr.length; i < len; i++){}for...infor (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 ('lil'); fragment. appendChild (li); li. innerHTML = 'did' + digitToZhdigit (index + 1) + 'name:' + item [0] + 'air quality: '+' <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 use let or const to declare all local variables without using the var keyword. By default, const is used unless the variable needs to be reassigned. Const is used to declare constants. let is a new way to declare variables. With block-level scopes, it is closed by curly brackets. In this way, access to variables under various nesting conditions is not considered.

var foo = true;if(foo) { let bar = foo*2; bar =something(bar); console.log(bar);}console.log(bar); // RefenceError

See https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md for details

Extension 2: You can use arrow functions => to write shorter functions.

MDN Arrow functions

numbers.forEach(numer => {});

Array sorting

Sort () method

By default, the toString () method of the array item is called for transformation, and then the array is sorted from small to large by comparing the string Order (ASCII code ).
To avoid comparing numeric strings, "10" is placed before "5". sort () accepts the compare () parameter of a comparison function and compares the values.

function compare(a, b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; }  }

If the return value of this function is less than 0, a is placed before B. If the return value is greater than 0, B is placed before a. If the return value is equal to 0, the relative positions of a and B remain unchanged. The last returned result is an ascending array. We can also exchange the values returned by the comparison function to generate a descending sorting result.
In addition, if the number is compared, the compare () function can be simplified as follows (where a-B is in ascending order and B-a is in descending order)

function compare(a, b) { return a - b;}

Use instances

Sorts attributes of a specific image.

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); // sort objectList by age. sort (function (a, B) {return. age-b.age });

You can sort a column in a multi-dimensional array.

Var aqiData = [["Beijing", 90], ["Shanghai", 50], ["Fuzhou", 10], ["Guangzhou", 50], ["Chengdu", 90], ["Xi'an", 100]; aqiData. sort (function (a, B) {return a [1]-B [1] ;}); console. table (aqiData); // output to the console as a table for visual debugging

Reverse () method

Returns an array in reverse order.

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

Function Classification of other array operation methods

Add an array element

ArrayObj. push ([item1 [item2 [... [itemN]); // Add one or more new elements to the end of the array, and return the new length of the array arrayObj. unshift ([item1 [item2 [... [itemN]); // adds one or more new elements to the array. The elements in the array are automatically removed and the new length of arrayObj is returned. splice (insertPos, 0, [item1 [, item2 [,... [, itemN]); // insert one or more new elements to the specified position of the array. The inserted element is automatically removed and "" is returned "". If the second parameter is not 0 (number of items to be deleted), the value can be replaced. Arr [array. length] = [] // Add a new item at the end of the array using the length attribute

Deletion of array elements

ArrayObj. pop (); // remove an element from the end and return the arrayObj value. shift (); // remove an element from the front end and return the element value. The elements in the array are automatically moved forward to arrayObj. splice (deletePos, deleteCount); // deletes the specified number of deleteCount elements starting from deletePos in the specified position, and returns a new array composed of the removed elements.

Truncation and merging of array elements

ArrayObj. slice (startPos, [endPos]); // return part of the array in the form of an array. Note that the elements corresponding to endPos are not included. If endPos is omitted, all elements after startPos are copied as arrayObj. concat ([item1 [, item2 [,... [, itemN]); // concatenates multiple arrays (or strings, or arrays and strings) into an array and returns a new connected array.

Copy an array

ArrayObj. slice (0); // returns the copy array of the array. Note that it is a new array instead of pointing to arrayObj. concat (); // returns the copy array of the array. Note that it is a new array, not pointing

Index of the element specified by the Array (can be used with splice)

Arr. indexOf (searchElement [, fromIndex = 0]) // returns the index position of the first found element (using the full comparison operator =) in the array; if not found,-1 is returned. FromIndex determines the start position, which can be omitted. LastIndexOf () // is the same as indexOf (), but it is searched from the end.

Stringized Array

ArrayObj. join (separator); // returns a string that connects each element value of the array and is separated by separator.

It can be seen as a reverse operation of split ().

Sum of array values

Array. reduce (function (accumulator, currentValue, currentIndex, array), initialValue) // apply a function to each element in the array (from left to right) and reduce it to a single value, returns the result var total = [0, 1, 2, 3] of the cumulative function processing. reduce (function (sum, value) {return sum + value ;}, 0); // total is 6

Summary

The above section describes the common Array Operation Skills in JavaScript. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.