Data Type summary--array (array type)

Source: Internet
Author: User
Tags array length prev

Original

The original Book of Jane: Https://www.jianshu.com/p/1e4425383a65

Outline

Objective
1. Related concepts of array type
2. There are two basic ways to create an array
3. How to detect if a variable is an array
4. Array traversal: for...in statement
5. Common methods of arrays

Objective

Data types are what each language needs to master, and mastering the use of each type of data is essential to mastering the language. And I also wrote a series of blogs about the data type, which contains a knowledge and understanding of the concept of a data type and the methods that are used frequently. Here are some of my understanding and understanding of the array type and I hope to be helpful to the reader. And this is a previous article about ES6, and then there will be a summary of the new knowledge about the ES6 array.

1. Related concepts of array type

1, the array is a special variable, he is composed of multiple array elements, you can save a number of different types of data. The existence of an array is to solve the limitation that a variable can only store one data, and using an array to hold multiple data items.
2, the declaration of the array is different from the declaration of the variable, you need to create the array through the new array ().
3. The index of each array element is unique and can be indexed to assign a value to the specified array element or to access the specified array element.
4. The array in ECMAScript is an ordered list of data, and unlike other languages, each item of the ECMAScript array can hold different data of any type. The size of the ECMAScript array can be dynamically adjusted, i.e. it can grow automatically as the data is added to accommodate the new data.

var colors = ["Red", "Bule", "green"];colors[99] = "BLACK"; Console.log (Colors.length);//100console.log (colors[98]);// Undefinedconsole.log (colors[99]);//black

5. JavaScript supports only one-dimensional arrays, not multidimensional arrays. JavaScript allows the elements of an array to be declared as a new array, thus simulating a multidimensional array.

var personel = new Array ();p ersonel[0] = new Array ();p ersonel[0][0] = "NAME0";p ersonel[0][1] = "AGE0";p ersonel[0][2] = "Ad Dress0 ";p ersonel[1] = new Array ();p ersonel[1][0] =" Name1 ";p ersonel[1][1] =" Age1 ";p ersonel[1][2] =" Address1 ";p Ersonel [2] = new Array ();p ersonel[2][0] = "Name2";p ersonel[2][1] = "Age2";p ersonel[2][2] = "Address2"; Console.log (personel);
2. There are two basic ways to create an array

1. Use the array constructor

var colors = new Array (), var colors = new array, var colors = new Array ("Red", "Blue", "green");

2, using the array literal notation, as with the object, when using the array literal notation, also does not call the array constructor.

var colors = ["Red", "Blue", "green"];var colors[colors.length] = "BLACK";
3. How to detect if a variable is an array

1, using the instanceof operator (when using the framework, the global execution environment in different frameworks may be problematic)

var colors = ["Red", "Bule", "green"];var Isarr = Colors instanceof Array;console.log (Isarr);

2. ES5 new Array.isarray () method to determine if a value is an array

var isArr2 = Array.isarray (colors); Console.log (ISARR2);
4. Array traversal: for...in statement

In JS, an array is not a data type, and the data type of an array is actually an object. The for.....in statement in JS enables traversal of all properties of an object. You can also use the for...in statement to implement traversal of all elements of an array for (var i in array) {}. Principle: There are several elements in the array, for. The in statement is executed as many times as the loop executes. At each execution, the subscript of the current array element is stored in the variable i

var row = [' Zhangsan ', ' Lisi ', ' Wangwu ', ' Xiaoqiang '];for (var i in row) {     //document.write (i + ': ' + row[i] + ' <br> ');     Console.log (Row[i]);} Zhangsan//lisi//wangwu//xiaoqiang
5, array of common methods 5.1, stack method: Push () and pop ()

The ECMAScript array provides an action method that allows the array to behave like a stack: a data structure that can restrict insertions and deletions, lifo:last-in-first-out LIFO, insertion of items in a stack called push-in, removal called eject
The ECMAScript array provides the push () and Pop () methods to implement a stack-like behavior

var colors = new Array (), var count = Colors.push ("Red", "green"), Console.log (count),//2//push method pushes the value and returns the length of the array count = Colors.push ("Black"); Console.log (count);//3var item = Colors.pop ();//pop method pops up the last entry of the array and returns the item Console.log (item);// Blackconsole.log (colors.length);//2
5.2. Queue method: Push () and shift ()

Access rules for queue data structures are FIFO (first-in-first-out first-out, queues add items at the end of the list, remove items from the front end of the list)
Using push to add items to the end of the array and using the shift () method to get the array front-end items, you can use the array as you would with the queue

var colors = new Array (), var count = Colors.push ("Red", "green"), Console.log (count),//2//push method pushes the value and returns the length of the array count = Colors.push ("Black"); Console.log (count);//3var item = Colors.shift ();//shift method pops the first item of the array and returns the item Console.log (item);// Redconsole.log (colors.length);//2
5.3. Unshift () method

ECMAScript also provides an array of unshift () methods for the arrays. Use the Unshift () method to add any item to the front of the array and return the array length.
Use the Pop () method to get the items at the end of the array.
The combination of the Unshif () method and the Pop () method can simulate a queue in the opposite direction, that is, adding items to the front of the array, removing items from the end of the array.

5.4. Sort by: reverse () and sort ()

There are already two methods in the array that can be used to reorder directly: reverse () and sort ().

Reverse (): The method reverses the order of the array

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

The sort () method arranges the array items in ascending order, that is, the smallest value is at the front and the largest value is the last. To implement sorting, the sort () method invokes the ToString () transformation method for each array, and then compares the strings to determine how to sort, even if each item in the array is a numeric value, and the sort () method compares the string.

var values = [0,1,5,10,15];values.sort (); Console.log (values);//(5) [0, 1, 10, 15, 5]
5.5. Concat () method

The Concat () method is used to push an item or items into an array and return an array after the composition.

var colors = ["Red", "Bule", "green"];var colors2 = Colors.concat ("Yellow", ["Black", "Brown"]), console.log (colors);//(3 ) ["Red", "Bule", "Green"]console.log (colors2);//(6) ["Red", "Bule", "green", "yellow", "black", "Brown"]
5.6. Slice () method

The slice () method is used to export one or more items from an array to return a new array consisting of these items.

var colors = ["Red", "Bule", "green", "yellow", "purple"];var colors2 = Colors.slice (1); var colors3 = Colors.slice (1,4); Console.log (colors);//(5) ["Red", "Bule", "green", "yellow", "Purple"]console.log (colors2);//(4) ["Bule", "Green", " Yellow "," Purple "]console.log (COLORS3);//(3) [" Bule "," green "," yellow "]
5.7. Splice () method

The splice () method is used to delete, insert, and replace one or more items in an array.

1. As the element in the delete array var colors = ["Red", "green", "blue"];var removed = Colors.splice (0,1);//delete the first item in the array starting with 0 console.log (colors) ;//(2) ["Green", "Blue"]console.log (removed);//["Red"]//2, used to insert array elements var colors = ["Red", "green", "blue"];var inserted = Colors.splice (0,0, "Yellow", "orange");//Insert two console.log (colors) in the position of 0 in the array;//(5) ["Yellow", "orange", "Red", "green", "Blue"]console.log (inserted),//[]//3, replacing the elements in the array var colors = ["Red", "green", "blue"];var inserted = Colors.splice (0,1, " Yellow "," orange ");//Delete the 0 starting 1 entries on the array and insert two console.log (colors);//(4) [" Yellow "," orange "," green "," Blue "]console.log ( inserted);//["Red"]
5.8. Location method: Find the location of the element--indexof () and LastIndexOf ()

ECMAScript added two location methods for an array: IndexOf () and LastIndexOf ()
Both methods receive two parameters: the item to find and an index that represents the location of the lookup start (optional)
Both methods return the position of the item to find in the array, and no return-1 is found, compared to the strict congruent method used in the lookup process
indexOf () is searched starting from the first, lastIndexOf () is looking back from the end

5.9. Iterative method: Every (), some (), filter (), map (), ForEach ()

ECMAScript defines 5 iterative methods for an array.
Each method receives two parameters: the function to run on each item and the scope object that runs the function (optional)--affects the value of this
The functions passed in these methods receive three parameters: the value of the array item, the position of the item in the array, and the group object itself.
Iterative methods need to pass in functions running on each item, which is the function that needs to operate on each item, so that you know what to do with each item of the array.

Every (): Returns True if each item of the array satisfies the condition, returns False if one item is not satisfied

var numbers = [1,2,3,4,5,4,3,2,1];var Everyresult = Numbers.every (function (item,index,array) {    return (item > 2);    //return (Index <);//true}); Console.log (Everyresult);//false

Some (): Returns True if an item of the array satisfies the condition, or false if no condition is satisfied

var numbers = [1,2,3,4,5,4,3,2,1];var Someresult = Numbers.some (function (item,index,array) {    return (item > 2);    Return (index >);//false}); Console.log (Someresult);//true

Filter (): Filters the items that meet the criteria

var numbers = [1,2,3,4,5,4,3,2,1];var Filterresult = Numbers.filter (function (item,index,array) {    return (item > 2 );    Return (Index > 4);//(4) [4, 3, 2, 1]}); Console.log (filterresult);//(5) [3, 4, 5, 4, 3]

Map (): Do the same for each item in an array

var numbers = [1,2,3,4,5,4,3,2,1];var Mapresult = Numbers.map (function (item,index,array) {    return (item * 2);}); Console.log (Mapresult);//(9) [2, 4, 6, 8, 10, 8, 6, 4, 2]

foreach (): Each item in an array does the same thing, unlike map (), the map () method copies an array copy and then operates on each element in the group, but foreach () operates on the array itself.

var numbers = [1,2,3,4,5,4,3,2,1];var Foreachresult = Numbers.foreach (function (item,index,array) {//1     item = Item * 2 ;//1//2     Array[index] = array[index] * 2;//2    Array[index] = Item * 2;//3//     console.log (item*2 = = = Array[index ]);//true//     Console.log (Array[index);}); Console.log (Foreachresult);//undefinedconsole.log (numbers);//1, (9) [1, 2, 3, 4, 5, 4, 3, 2, 1]//2, (9) [2, 4, 6, 8, 10, 8, 6, 4, 2]//3, (9) [2, 4, 6, 8, 10, 8, 6, 4, 2]
5.10. Reduction method: Reduce () and reduceright ()

There are two new ways to reduce arrays in ECMAScript 5: Reduce () and reduceright (). Both of these methods iterate over all the items of an algebraic group and then build a value that is ultimately returned. The reduce () method iterates from the first item in the array, and Reduceright () starts from the last item in the array. Both methods receive two parameters: a function that is called on each item and an initial value that is used as the basis for narrowing (optional). The operation functions passed to reduce () and Reduceright () receive 4 parameters: the previous value, the current value, the index of the item, and the array object.

var values = [1,2,3,4,5];var sum = values.reduce (function (prev,cur,index,array) {    return prev + cur;}) Console.log (sum);//15

  

Data Type summary--array (array type)

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.