Javascript:array type

Source: Internet
Author: User

The array type in JavaScript differs greatly from the 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 to accommodate new data as the data is added automatically .

There are two basic forms of creating an array.

1.Array Constructors

var New Array ();

If you know beforehand how many items you want to save, you can also pass that number to the constructor, which automatically becomes the value of the length property.

var New Array (3);

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

var New Array ("Shanghai", "Beijing", "Shenzhen");

You can omit the new operator when creating an array:

var // create an array with 3 elements

2. Array literal notation

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

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

When reading and setting the value of an array, use square brackets and provide a numeric index based on 0 (based on 0 that is the 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" // Modify the second item "Beijing" to "Hongkong"cities[3] = "Taiwan"    //  Add a new item

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

var cities = ["Shanghai", "Beijing", "shenzhen"= 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"= "Hongkong";
2.1 Detecting arrays

ECMAScript5 adds the Array.isarray () method to determine whether a value is an array, regardless of which global execution environment it is created in. Use the following:

if (Array.isarray (value)) {    // to perform certain operations on an array}
2.2 Conversion method

All objects have tolocalestring (), toString (), and valueof () methods. The ToString () method in which the array is called returns a comma-delimited string that is stitched together as a string of each value in the array. examples such as:

var cities = ["Shanghai", "Beijing", "Shenzhen"];alert (Cities.tostring ());    // shanghai,beijing,shenzhenalert (cities.valueof ());    // shanghai,beijing,shenzhenAlert (cities);              // Shanghai,beijing,shenzhen

Note: Because alert () needs to receive the string argument, it calls the ToString () method in the background, so it will get the same result as the ToString () method called directly.

In addition, the tolocalestring () method often returns the same values as ToString () and valueof (), unlike the tolocalestring () method, which is called for each item in order to get the value of each item. Instead of the ToString () method. For example:

varP1 ={tolocalestring:function () {            return"P1 tolocalestring"; }, ToString:function () {            return"P1 toString";    }    }; varP2 ={tolocalestring:function () {            return"P2 tolocalestring"; }, ToString:function () {            return"P2 toString";    }    }; varp =[P1, p2];    Alert (p);    Alert (p.tostring ()); Alert (p.tolocalestring ());

The result shows that the first and second rows call the ToString method, and the third row calls the toLocaleString method.

The array inherits the toLocaleString (), toString (), and valueof () methods, which, by default, return array items as comma-delimited strings. By using a 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,shenzhenalert (Cities.join (",")); // shanghai,beijing,shenzhenalert (cities.join ("|")); // Shanghai|beijing|shenzhen
2.3 Stack method

A stack is a last-in, first-out (LIFO) data structure that inserts and removes data items from the stack only at the top of the stack . The JavaScript array provides the push () and Pop () methods for implementing a stack-like behavior.

Push () method

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

var New Array (); var count = Params.push ("A", "B"), alert (params);   // A, balert (count);   // 2

As can be seen from the above example, the push () method returns the number of inserted items.

Pop () method

Removes the last item from the end of the array, reduces the length of the array, and returns the item that is removed.

var New Array (); var count = Params.push ("A", "B", "C"); var item = params.pop (); alert (item);     // Calert (params.length);   // 2
2.4 Queue method

The access rules for the data structure of a queue are first in, out (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, which moves the first item in the array and returns the item, modifying the length property of the arrays.

var New Array (); var count = Params.push ("A", "B", "C"var item = Params.shift ();  // get the first alert (item);    // aalert (params.length);   // 2

Unshift () method

JavaScript also provides the Unshift () method, which 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"  //  1  alert (params); //  a  var  Count2 = Params.unshift ("b"  //  2  alert (params); //  B,a  var  Count3 = Params.unshift ("C", "D"  //  C,d,b,a  

It is observed that if there are multiple items in a unshift () at a time, it inserts the items sequentially into the array, that is, the first parameter is inserted at the front. As in the example above, insert "a" for the first time, insert "B" at the front of the array for the second time, and the third time there are multiple items, but the order is C before, and d behind.

2.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 array items in ascending order. In order to implement sorting, thesort () method invokes the ToString () transformation method for each array item, and then compares the resulting string. Therefore,the sort () 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 is basically meaningless, and what we need is to sort the values. The sort () method can receive a comparison function as a parameter in order to specify a collation.

The comparison function receives two parameters, returns a negative number if the first argument should precede the second argument, returns 0 if the two arguments are equal, or 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
2.6 Operating methods

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 parameters to the end of the copy and 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 // 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 an item . When only one parameter is returned, all items from the starting item to the end of the array, when there are two parameters, return 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/ /// Shanghai,shenzhen

Splice () method

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

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

    var cities = ["Beijing", "Shanghai", "Shenzhen", "Guangzhou"];cities.splice (1,3); Alert (cities) ;   // Beijing
  • Insert To insert any number of items into the specified location. Specify 3 parameters: Start position, 0 (number of items to delete), item to insert

    var cities = ["Beijing", "Shanghai", "Shenzhen", "Guangzhou"];cities.splice (1,0, "Hongkong"); Alert (cities);   // Beijing,hongkong,shanghai,shenzhen,guangzhou
  • replace to replace the item at the specified location. Specify 3 parameters: Start position, item to delete, any item to insert.

    var cities = ["Beijing", "Shanghai", "Shenzhen", "Guangzhou"];cities.splice ("Hongkong"); Alert (cities);   // Beijing,hongkong,guangzhou
2.7 Placement Method

There are two location methods in javascript: the IndexOf () method and the LastIndexOf () method. Both methods receive two parameters: the item to find and (optionally) the index that represents the location of the lookup start point .

The IndexOf () method means looking backwards from the beginning of the array, and LASTINDEXOF () looks forward from the end of the array. They all return the position of the found item in the array, and return 1 if not found. The same is used when the first argument is compared to each item in the array.

var nums = [1,2,3,4,5,6];alert (nums.indexof (//  2//  4alert (Nums.indexof (3,1));   // 2alert (nums.lastindexof (bis));   // 3
2.8 Iterative Methods

JavaScript provides 5 iterative methods for an array. Each method receives two parameters: the function to run on each item and, optionally, the scope object that runs 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 array object itself .

    • every (): returns True if the given function is run for each item in the array, and if the number of rows returns true for each item
    • filter (): runs the given function for each item in the array, returning the arrays that are composed of the items that return true
    • Foreeach (): runs the given function for each item in the array, with no return value
    • map (): each item in an array runs the given function, returning a function that consists of the result of each function call.
    • some (): runs the given function for each item in the array, and returns True if any of the entries returns true

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

2.9 Merging methods

There are two ways to merge arrays in javascript: 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. where the reduce () method starts with the first item in the array, and Reduceright () begins with the last item in the array.

They can all receive two parameters: a function that is called on each item and (optionally) the initial value for 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 parameter is the first item of the array, and the second 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+   //  

The first time the callback function is executed, Prev is 1,cur is 2. The second time, Prev is 3 (1+2), 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.

Javascript: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.