JavaScript Grooming-Arrays and class arrays

Source: Internet
Author: User
Tags array example

An array is a set of data that is represented by a contiguous memory address in memory, where the array name is the first address of a contiguous memory address, and what is an array of classes? The class array, as its name implies, is an array, but not a real array, modeled by the attributes of objects and arrays, with the length property, but without the method of the array. Let's talk about arrays.

There are two ways to create an array:

    • var array name = []; Array literals (recommended)
    • var array name = new Array (); constructor function

Eg:var arr1 = new Array ();//Create an empty array

var arr2 = new Array (10); Pass a parameter that is a numeric type when (an integer) represents the length of an array, as in this case the length of the array arr2 is 10

var arr3 = new Array ("A", "B"); Create an array that contains a and b

Properties of the array:

Length is from 1, but the subscript of the array starts from 0, don't confuse it.

Array of methods:

the length of the array is divided into two categories

First: Methods that can change the original array

    • push () adds an element to the end of the array and returns the new length      
var arr1 = ["Apple", "Orange"]var arr2 = Arr1.push ("peach"); Console.log (ARR2) ; // the new length of the array is 3console.log (ARR1); // output to Apple Orange Peach
    • pop () deletes the last element of the array and returns the Delete element    
var arr1 = ["Apple", "orange", "peach", "banana"]var arr2 = arr1.pop (); Console.log (ARR2) ; // the array deletion element is Bananaconsole.log (arr1); // output to Apple Orange Peach
    • unshift () adds one or more elements to the beginning of the array and returns the new length
var arr1 = ["Tom", "Lily", "Lucy"];arr1.unshift ("Mack", "angle"//5 (array new length) Mack angle Tom Lily Lucy
    • shift () deletes the first element of the array, returning the deleted element
var arr1 = ["Tom", "Lily", "Lucy"
    • splice () deletes an array element and adds a new element to the array

Delete: You can delete any number of items by specifying only 2 parameters: the location of the first item to delete and the number of items to delete. For example, splice (0,2) deletes the first two items in the array.

Insert: You can insert any number of items to a specified location, providing only 3 parameters: Start position, 0 (number of items to delete), and items to insert. For example, splice (2,0,4,6) inserts 4 and 6 starting at position 2 of the current array.  

Replace: You can insert any number of items at the specified location and delete any number of items at the same time by specifying 3 parameters: The starting position, the number of items to delete, and any number of items to insert. The number of items inserted does not have to be equal to the number of items deleted. For example, splice (2,1,4,6) deletes the item of the current array position 2.

Then insert 4 and 6 starting from position 2.

vararr = [1,3,5,7,9,11];vararrremoved = Arr.splice (0,2); Console.log (arr); //[5, 7, 9, one]Console.log (arrremoved);//[1, 3]varArrRemoved2 = Arr.splice (2,0,4,6); Console.log (arr); //[5, 7, 4, 6, 9, one]Console.log (ARRREMOVED2);// []varArrRemoved3 = Arr.splice (1,1,2,4); Console.log (arr); //[5, 2, 4, 4, 6, 9, one]Console.log (ARRREMOVED3);//[7]
    • reverse () reverses array elements
var arr = [12,23,45,56,78,89];arr.reverse (); Console,log (arr); //  A.

    • Sort () array sorting (from small to large)

When sorting, sort () calls the ToString () method that invokes each array, and the string is compared, so the original array changes

ARR2 = [  13, 24, 3, 51] (the meta-array is changed) , 3//  [3,, Wuyi]

    If you want the original array to not be changed, you can write a comparison function as an argument to specify which value precedes it, the comparison function receives two parameters, and if the first argument should precede the second one returns a negative number, and if two arguments are equal, it returns 0, a positive number is returned if the first parameter should be located after the second one. The following is a simple comparison function:

function Compare (value1, value2) {if (value1 < value2) {return -1Else if (value1 > value2) {return 1else  {return 0  = [3, 3 , Wuyi, +-- ]

The above is ascending (small to large), if you want to descending (from big to small), swap the comparison value.

The second type: The method of the original array cannot be changed

    • Join (separator) sets the element group of the array as a string, separator as a delimiter, or by default with a comma delimiter, which receives only one argument: the delimiter.
var arr =   [----------* * * *//   [1, 2, 3] (the original array does not change)
    • concat () concatenate two or more arrays, and return the result, how no parameter is equivalent to the first clone of the array
var arr = [1,2,3,4]var arr1 = Arr.concat (78,56); Console.log (ARR,ARR1); // arr:1 2 3 4 // arr1:1 2 3 4
    • ToString () turns into a string
    • Slice () intercepts the length of the array, returning the element from the start subscript to the end subscript, if there is only one parameter, which is to intercept the parameter subscript to the last element of the array

arr = [3,12]; var test = Arr.slice (3); Console.log (test); // 3,12 var test1 = Arr.slice (1,4); Console.log (test1); // 24,51,3Console.log (arr); // 13,24,51,3,12 The original array does not change

now to the class array (arguments,arraylike)

Class array has the length property, but there is no method of array, essentially an object, what kind of array is it like?

// Class Array Example var a = {' 1 ': ' GG ', ' 2 ': ' Love ', ' 4 ': ' Meimei ', Length:5}; Array.prototype.join.call (A,' + '); // ' +gg+love++meimei ' // examples of non-class arrays var c = {' 1 ': 2};   // No Length property is not an array of classes

Since the class array does not have an array method, what if it is forcibly invoked? With the push () and Splice () methods of the array, the forced invocation of the property expands according to the position of the length property.

var obj = {  0: "A",  1: "B",  Push:Array.prototype.push,  Splice:array. Prototype.splice}

A function that determines whether an object is an array of classes, as follows

functionisarraylike (o) {if(O &&//O is not null, undefined, etc.        typeofo = = = ' object ' &&//o is an objectIsfinite (o.length) &&//O.length is a finite numberO.length >= 0 &&//O.length is non-negativeO.length===math.floor (o.length) &&//o.length is an integerO.length < 4294967296)//O.length < 2^32        return true;//Then o are array-like    Else        return false;//Otherwise It is not}

An array of classes can be converted into arrays, and an array of classes is essentially an object, and a series of methods that can call an array after being transferred to a group

1.array.prototype.slice.call (arraylike): Converts arraylike to an array object, which can be directly called by the method of the array
Array.prototype.slice.call (arraylike). ForEach (function(element,index) {  //  You can manipulate each element freely)

Arrray.prorotype.slice borrowed the slice method from the prototype, returning an array, slice the internal implementation method

function (start,end) {        varnew  Array ();         = Start | | 0;          This // after using call, this points to the class array object       for (var i = start; i < end; i++) {             Result.push (this[i]);        }         return result;   

A general-purpose conversion function

var function (s) {      try{          return  Array.prototype.slice.call (s);       Catch (e) {              var arr = [];                for (var i = 0,len = s.length; i < Len; i++) {                    = s[i];               }                return arr;      

2.array.from ()

Array.from () is a new method in ES6 that can convert two types of objects into real arrays: Class array objects and Ergodic (iterable) objects, including ES6 new data structure set and map.

3., extension operator (... )
Also the new content in ES6, the extension operator (...). You can also convert some data structures to arrays

JavaScript Grooming-Arrays and class arrays

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.