Javascript:array Type Comprehensive Analysis _ Basic knowledge

Source: Internet
Author: User
Tags prev first row javascript array

The array type in JavaScript differs greatly from an array in other languages. each item in JavaScript can hold any type of data. also, the size of the JavaScript array can be dynamically adjusted and can grow automatically as the data is added to accommodate the new data .

There are two basic forms of creating an array.

1.Array Constructors

var cities = new Array ();

If you know in advance the number of items you want to save, you can also pass the number to the constructor, which automatically becomes the value of the length property.

var cities = new Array (3);

You can also pass to the array constructor the items that should be included in the array.

var cities = new Array ("Shanghai", "Beijing", "Shenzhen");

You can omit the new operator when you create an array:

var cities = Array (3); Create an array that contains 3 elements

2. Array literal notation

The literal representation of an array is represented by a pair of square brackets that contain an array item, separated by commas between multiple array items, as follows:

var cities = ["Shanghai", "Beijing", "Shenzhen"];
var cities = []; Create an empty string

When reading and setting the value of an array, you use square brackets and provide a numeric index based on 0 (0 is the start count from 0, the first item is 0, the second item is 1, and so on), as follows:

var cities = ["Shanghai", "Beijing", "Shenzhen"];
Alert (cities[0]);  "Shanghai"
cities[1] = "hongkong";//Modify the second item "Beijing" as "Hongkong"
cities[3] = "Taiwan"  //Add a new item

The number of items in the array is stored in the Length property, which is not read-only . Therefore, you can set the Length property to remove an item from the end of the array or to add a new item to the array.

var cities = ["Shanghai", "Beijing", "Shenzhen"];
Cities.length = 2;
Alert (cities[2]);  Undefined

Use this property of length to add a new item at the end of the array:

var cities = ["Shanghai", "Beijing", "Shenzhen"];
Cities[cities.length] = "Hongkong";

1. Detection array

ECMAScript5 has added the Array.isarray () method to determine whether a value is an array, regardless of which global execution environment it is created in. Usage is as follows:

if (Array.isarray (value)) {
  //the array performs certain actions
}

2. Conversion methods

All objects have tolocalestring (), toString (), and valueof () methods. where the ToString () method that invokes the array returns a comma-delimited string that is spliced by a string of each value in the array. For example:

var cities = ["Shanghai", "Beijing", "Shenzhen"];
Alert (cities.tostring ());  Shanghai,beijing,shenzhen
alert (cities.valueof ());  Shanghai,beijing,shenzhen
alert (cities);       Shanghai,beijing,shenzhen

Note: Because alert () needs to receive a string parameter, it calls the ToString () method in the background, so it gets the same result as the direct invoke ToString () method.

In addition, the tolocalestring () method often returns the same value as ToString () and valueof (), and in order to get the value of each item, the tolocalestring () method for each item is invoked . Rather than the ToString () method. For example:

var P1 = {
    tolocalestring:function () {return
      "P1 tolocalestring";
    },
    tostring:function () {
      retur N "P1 toString";
    }
  ;

  var P2 = {
    tolocalestring:function () {return
      "P2 tolocalestring";
    },
    tostring:function () {
      R Eturn "P2 toString";
    }
  ;

  var p = [P1, p2];
  Alert (p);
  Alert (p.tostring ());
  Alert (p.tolocalestring ());

The results show that the first row and the second row call the ToString method, and the third row calls the toLocaleString method.

Array inherits the toLocaleString (), toString (), and valueof () methods, which, by default, return an array entry as a comma-delimited string. By using the Join () method, you can use different characters to split a string and then return a string that contains all the array items.

var cities = ["Shanghai", "Beijing", "Shenzhen"];
Alert (cities);     Shanghai,beijing,shenzhen
alert (Cities.join (","));//Shanghai,beijing,shenzhen
alert (cities.join ("|")); /Shanghai|beijing|shenzhen

3. Stack method

A stack is a LIFO (LIFO) data structure in which the insertion and removal of data items can only occur at the top of the stack. JavaScript arrays provide push () and Pop () methods to implement stack-like behavior.

Push () method

You can receive any number of parameters, add them to the end of the array, and modify the length of the array.

var params = new Array ();
var count = Params.push ("A", "B");
alert (params); A,b
alert (count);  2

As you can see from the example above, the push () method returns the number of inserted entries.

Pop () method

Removes the last item from the end of the array, reducing the length of the array and returning the removed item.

var params = new Array ();
var count = Params.push ("A", "B", "C");
var item = Params.pop ();
alert (item);  C
alert (params.length);  2

4. Queue method

The access rule for the data structure of the queue is FIFO, which is to add items from the end of the queue and remove items from the front end of the queue.

Shift () method

The shift () method is provided in JavaScript to move the first item in the divisor group and return the item, while modifying the length property of the array.

var params = new Array ();
var count = Params.push ("A", "B", "C"); 

var item = Params.shift (); Get the first
alert (item);  A
alert (params.length);  2

Unshift () method

JavaScript also provides a unshift () method that adds any item to the front of the array and returns the length of the new array.

var params = new Array ();
var count1 = Params.unshift ("a");
alert (COUNT1); 1
alert (params);//a
var count2 = Params.unshift ("b");
alert (COUNT2); 2
alert (params);//B,a
var count3 = Params.unshift ("C", "D");
alert (params); C,d,b,a

Observations found that if there are multiple entries in a unshift (), it inserts the items into the array in order that the first argument is inserted at the front. As in the example above, insert "a" for the first time, insert "B" at the top of the array for the second time, and multiple items on the third, but the order is C before and D in the back.

5. Reordering methods

The array provides two methods for reordering directly.

Reverse () method

The reverse () method reverses the order of the array items.

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

Sort () method

By default, the sort () method arranges the array items in ascending order. To implement sorting, thesort () method invokes the ToString () transformation method for each array item, and then compares the resulting string. Therefore, thesort () method compares a string .

var values = [3,5,53,2,34];
Values.sort ();
alert (values); 2,3,34,5,53

However, we can say that this sort of sorting is basically meaningless, and what we need is to sort the numbers. The sort () method can receive a comparison function as an argument to specify the collation.

The comparison function receives two arguments, returns a negative number if the first argument should precede the second argument, and returns 0 if the two arguments are equal, and returns a positive number if the first argument is after the second argument.

function Compare (value1, value2) {
  if (value1 < value2) {
    return-1;
  } else if (value1 > value2) {
   return 1;
  } else {return
    0;
  }
}
var values = [3,5,53,2,34];
Values.sort (compare);
alert (values); 2,3,4,34,53

6. Method of operation

Concat () method

You can create a new array based on all the items in the current array. This method creates a copy of the current array, then adds the parameter to the end of the replica, and then returns the newly constructed array. If one or more arrays are passed to the concat () method, each item in the array is added to the array.

var arrays = ["A", "B", "C"];
var arrays2 = Arrays.concat ("D", ["E", "Fe"]);
alert (arrays); A,b,c
alert (ARRAYS2);//A,b,c,d,e,f

Slice () method

Creates a new array based on one or more items in the current array. The slice () method can receive one or two parameters, that is, to return the starting and ending positions of the items . When one argument returns all items from the starting entry to the end of the array, when there are two arguments, returns the entry between the start and end positions (excluding the end item). the Slice () method does not affect the original array.

var cities = ["Beijing", "Shanghai", "Shenzhen", "Guangzhou"];
var cities2 = Cities.slice (1);
var cities3 = Cities.slice (1,3);

alert (CITIES2); Shanghai,shenzhen,guangzhou 
alert (CITIES3);//Shanghai,shenzhen

Splice () method

The splice () method is primarily used to insert items into the middle of the array, using 3 different ways:

• Delete can delete any number of items, specify 2 parameters: the first item to delete and the number of items deleted, such as: Splice (1,3) deletes the 2nd, 3, 4 items in the array

var cities = ["Beijing", "Shanghai", "Shenzhen", "Guangzhou"];
Cities.splice (1,3);

Alert (cities); Beijing

• Inserts any number of items that can be inserted at the specified location. Specify 3 parameters: Start position, 0 (number of items to delete), items to insert

var cities = ["Beijing", "Shanghai", "Shenzhen", "Guangzhou"];
Cities.splice (1,0, "Hongkong");
Alert (cities); Beijing,hongkong,shanghai,shenzhen,guangzhou

• Replace items that can replace the specified location. Specifies 3 parameters: The start position, the item to delete, and any items to insert.

var cities = ["Beijing", "Shanghai", "Shenzhen", "Guangzhou"];
Cities.splice (1,2, "Hongkong");
Alert (cities); Beijing,hongkong,guangzhou

7. Location method

There are two location methods in javascript: the IndexOf () method and the LastIndexOf () method. Both methods receive two parameters: the Xiang (optional) To find indicates the index at which to find the start point.

The IndexOf () method represents a lookup backward from the beginning of the array, and LastIndexOf () starts looking forward from the end of the array. They both return the position of the found item in the array and return 1 if they are not found. Congruent is used when the first parameter is compared to each item in the array.

var nums = [1,2,3,4,5,6];
Alert (Nums.indexof (3)); 2
Alert (Nums.lastindexof (5));//4

alert (Nums.indexof (3,1));  2
alert (Nums.lastindexof (4,4));  3

8. Iterative method

JavaScript provides 5 iterative methods for an array. Each method receives two parameters: the function to run on each item and optionally run the scope object of the function-the value that affects this. Parameters that need to be passed in: The value of the array item, the position of the item in the array, and the group object itself.

every (): Runs the given function for each item in the array, returns true if the number of rows returns true for each item

filter (): Each item in an array runs the given function, returning an array of items that return true

Foreeach (): Run the given function for each item in the array with no return value

map (): Each item in an array runs the given function, which returns the function of the result of each function call.

some (): Runs the given function for each item in the array, and returns true if either entry returns True

None of the above methods will modify the values contained in the array.

9. Merge method

There are two ways to merge arrays in javascript: reduce () and reduceright (). Both methods iterate over all the items of the group, and then build a value that is eventually returned. where the reduce () method starts with the first item of the array, and Reduceright () begins with the last item in the array.

They can all receive two parameters: a function called on each item and (optionally) the initial value of the merge base. Functions passed to reduce () and Reduceright () receive 4 parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function will be automatically passed to the next item as the first argument. The first iteration occurs on the second item of the array, so the first argument is the first item of the array, and the second argument is the second item of the array.

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

The first time the callback function is executed, the prev is 1,cur is 2. The second time, Prev is 3 (1+2), and Cur is 3 (the value of the third item in the array), knowing that each entry is accessed.

Reduceright () acts similarly, except in the opposite direction.

The above Javascript:array type of comprehensive analysis is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.