The array object of JavaScript

Source: Internet
Author: User
Tags prev

The array type is the most commonly used type in ECMAScript.

I. Ways of declaring

1. Using the array constructor

var New Array ();

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

var New Array (Ten//   )

You can also pass the contained value to the array.

var New Array (' Hello ', ' world ', ' JS '); Console.log (arr);   // [' Hello ', ' world ', ' JS ']

You can also omit the new operator when using array.

var str = Array (3//  3

2. Array literal notation

var name = [' Mike ', ' John ', ' Kaer '];

Note: Do not want to declare an array like this,  var arr = [1, 2,]; , arr becomes an array of 3 items with a value of 1,2,undefined for each of the IE8 and earlier versions. In other browsers, it contains an array of item values, respectively.

Setting and getting the value of an array can be indexed by the way.

Second, Length property

The length property of an array is not just read-only, and you can either remove it from the end or add a new item to the array by setting this property.

var name = [' Mike ', ' John ', ' Kaer '= 2; Console.log (name[2]);  // undefined

If you set the Length property to be greater than the value of the array item, each new item will get the undefined value.

var names = [' Mike ', ' John ', ' Kaer '= 4; Console.log (names[//undefined 

Each time an item is added at the end of the array, the length property automatically updates the change in response. When you place a value beyond the current array size, the array recalculates its length, that is, the length value equals the last index plus 1.

var names =[];names[] = ' Mike '//  100

Three, array method

1. toString (): Returns a comma-delimited string that is stitched together as a string of each value in the array.

var arr = [a/

In fact, in order to create this string, the ToString () method of each item of the array is called.

var str1 = {    function() {        return ' Hello ';    }}; var str2 = {    function() {        return ' World ';    }};  var arr = [str1, Str2];console.log (arr.tostring ());   // Hello, World

You can also use the Join method to stitch arrays, and you can stitch strings by passing different delimiters. If the parameter is not passed or the argument is undefined, a comma is used as the delimiter. However, IE7 and earlier versions would consider using undefined as the delimiter.

2. valueOf (): The method returns an array

var ar = [[+]/[+]

3.pop (), push (Param1[,param2,....., param ...])

The push () method can receive any number of arguments, add them to the end of the array one by one, and return the length of the modified array.

The Pop () method removes the last item from the end of the array, reduces the length value of the array, and then returns the item that was removed.

var names = [' Mike ', ' John ', ' Kaer ']; var count = names.push[' Barret '//  4//4var item =   //  ' Barret '//  3

4. shift (), unshift ()

The Unshift () method can accept any number of parameters, add them individually to the front of the array, and return the length of the modified array.

The shift () method removes the last item from the end of the array, reduces the length value of the array, and then returns the item that is removed.

5. Reverse (), sort ()

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

var arr = [1, 2, 6, 4//  [4, 6, 2, 1]

The sort () method arranges the group items in ascending order, that is, the minimum value is at the front and the maximum is the last. The sort () method invokes the ToString () method of each array item and then compares the resulting string.

var  Nums = [1,2,4,10,5];nums.sort (); Console.log (nums);   // [1, Ten, 2, 4, 5]

The sort () method changes the original order based on the result of the test string, although 10 is greater than 2,4,5, but when a string comparison is made, ' 10 ' is in front of ' 2 ', ' 4 ', ' 5 '. The sort () method can receive a comparison function as a parameter so that we specify which value is in front. The comparison function receives two parameters, returns a negative number if the first argument should precede the second, and returns 0 if the two arguments are equal if the first parameter should be located after the second. Returns an integer.

function Compare (value1, value2) {    return value1 < value2? -1:1;}

This comparison function applies to most types of data, as long as it is passed as a parameter to sort.

var nums = [1,3,10,9, 4//  [1, 3, 4, 9, ten]

6. Concat (param1[,param2,... Paramn]): The receive parameter is added to the array based on the current array. In the absence of a pass parameter, only a copy of the current array is copied.

var names = [' Kaer ', ' Jhon ', ' Mike ']; var names2 = Names.concat (' David ', [' Smith ', ' Snow '//  [' Kaer ', ' Jhon ', ' Mike ', ' David ', ' Smith ', ' Snow ')

7. Slice (start, end): Creates a new array based on one or more of the current array. If there is only one argument, slice returns all items at the beginning of the specified position to the end of the current array. If there are two parameters, the method returns the entry between the start and end positions, but not the ending position. This method does not affect the original array . If the argument is negative, it represents the forward position from the end of the array, and the last subscript is-1. If the starting position is greater than the end position, an empty array is returned.

var nums = [1,2,3,4,5,6]; var nums2 = Nums.slice (2//  [3,4,5,6]var nums3 = Nums.slice (2, 5  // [3, 4, 5] var nums4 = Nums.slice (2,-1//  //[3,4,5]

8. Splice (): One of the most powerful array methods, mainly providing three usage. This method will change the original array.

  1. Delete: Delete any number of items that require 2 parameters, the position of the first item, and the number of items to delete. returns the item that was deleted.
    var nums = [1, 2, 3, 4, 5];nums.splice (//  [1, 2]//  [3, 4, 5]
  2. Insert: You can insert any number of items to a specified location, requiring 3 parameters: Start position, 0, and item to insert. Returns an empty array.
    var nums = [];nums.splice (1, 0, ' hello ', ' World '// [+], ' hello ', ' World ', 3]
  3. Replace: Inserts any number of items to the specified location, and the colleague deletes any number of items, requires 3 parameters, the starting position, the number of items to delete, and any number of items to insert. returns the item that was deleted .
    var nums = [];nums.splice (//  2//  [1, ' Hello ', ' World ', 3]

9. IndexOf () and LastIndexOf (): receives two parameters, the item to find, and an index that represents the location of the seven-point lookup. IndexOf from the beginning of the array, LastIndexOf looks forward from the end of the array. Returns the position of the lookup item in the array, or 1 if no case is found.

var numbers = [1, 2, 3, 4, 5, 6];
Console.log (Numbers.indexof (7)); -1console.log (Numbers.indexof (// 2

Every (), filter (), ForEach (), map (), some ()

None of these methods will modify the original array itself. They can all pass in two parameters, the first is the callback function callback for the array item operation, and the second parameter is the this value.

1. Every (): Runs the given function for each item in the array, and returns True if every item of the function returns True.

2. Filter (): Each item in an array runs the given function, and returns a list of the items that the function returns True.

3. ForEach (): Runs the given function for each item in the array. no return value.

4. Map (): Runs the given function for each item in the array, returning a list of the results of each invocation. the function is called only on the index with the value. callback The array element range is determined when the first callback is executed, and the newly added elements are not accessed by callback during map execution.

5. Some (): Runs the given function for each item in the array and returns true if any of the entries returns TRUE.

varNums = [1, 2, 3, 4, 5];varEveryresult = Nums.every (function(item, index, array) {return(Item > 2);}); Console.log (Everyresult); //falsevarSomeresult = Nums.every (function(item, index, array) {return(Item > 2);}); Console.log (Someresult); //truevarFilterresult = Nums.filter (function(item, index, array) {return(Item > 2);}); Console.log (Filterresult); //[3, 4, 5]varThisarg = {Num:1 };varMapresult = Nums.map (function(item, index, array) {return(Item * 2 + This. num);}, Thisarg); Console.log (Mapresult); //[3, 5, 7, 9, each]varNullarr = [];varMapresultnull = Nullarr.map (function(item, index, array) {return(Item * 2);}); Console.log (Mapresultnull); // []

One . reduce (), Reduceright (): Iterates through all the items of an algebraic group, and then constructs a final return value. Can pass two parameters, a function that is called on each item and the initial value of the recursive basis. A callback function can 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.

var nums = [1, 2, 3, 4]; var sum = nums.reduce (function(prev, cur, index, array) {    return prev +   //  ten

The array object of JavaScript

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.