JavaScript Base-----Arrays (Array)

Source: Internet
Author: User

Methods for creating arrays in 1.JavaScript:

(1). Use the array constructor:

var New Array ();    // create an empty array var New Array (5);   // when an integer is passed, an array of length 5 is created, and if a string is passed, the array that contains the string is created var New Array (5, "abc", +)    // Pass multiple elements, representing the creation of an array containing these elements, how many elements, how long is the length

(2). Use array literals:

var arr = []    // Create an empty array var arr = [,,,,,]    // only when the comma is passed, indicating the length of the array, Pass several commas with a length of several var arr = ["abc", 2, "123"]    // Create an array containing these elements

2. Some properties and methods of the array:

(1) length: Indicates the number of elements in the array

var arr = [1, "456", "ABC"]console,log (arr.length)      // Output 3 (number of elements)

    (2)   prototype : Adds a property or method to an array, after which all the created array objects will have this property or method (prototype is a global property, You can add a property or method to an array (the array itself is an object), or to any object, for example:

 //  Converts the values of the created array to uppercase letters  Array.prototype.Cap = function   () { for  (var  i = 0;i <  This . Length;i ++ this  [i] = this  [i].touppercase (); }}  //  Create an array, call the CAP () method  var  arr = ["Ssdj", "DF", "DSF", "s" ];arr. Cap ();  //  View results in the console  Console.log (arr) //  output [" Ssdj "," DF "," DSF "," S "]  

(3) push (): Adds one or more elements to the end of the array and returns the new length

var arr = [1, "2", "abc"];arr.push ("456"), Console.log (arr)    // Output [1, "2", " ABC "," 456 "]

(4) unshift (): Adds one or more elements to the beginning of the array and returns the new length

var arr = [1, "2", "abc"];arr.unshift ("Hello"); Console.log (arr)    // output ["Hello", 1, "2", "ABC"]

(5) pop (): Delete the last element of an array

var arr = [1, "2", "abc"];arr.pop (); Console.log (arr)    // Output [1, "2"]

(6) shift (): Delete the first element of an array

var arr = [1, "2", "abc"];arr.shift (); Console.log (arr)    // Output ["2", "ABC"] // when the array is empty, it returns undefined

(7) *join (): Make a string of all the elements of an array, including the comma in the array, and the arguments passed in the join () are equivalent to replacing the comma in the array with that parameter

var arr = ["A", "B", 2, "F"];console.log (Arr.join ())    // output string "a,b,2,f"//   Console.log (Arr.join ("-"))    // Output "a-b-2-f" when passing parameters

Use Join () to implement the repetition of the string:

function Fun (str,n) {    returnnew Array (n + 1). Join (str);} Console.log ("Hello", 3)    // output "Hello hello hello"// The n here is equivalent to the comma in the array, and the new Array (4) is equivalent to [,,,]

(8) *sort (): The elements of an array are sorted from small to large, but sort () converts the elements in the arrays to strings and then compares them, including the values, so the following occurs:

var arr = [12,5,43,252,3];arr.sort (); Console.log (arr)     / Output [12, 252, 3, 43 , 5]

To solve the above situation, you can create a comparison function and then call the function with sort ()

//The comparison function can pass two parameters, and returns a negative number if the NUM1 is before num2, and returns a positive number after the 0;NUM1 is num2 .functionFun (num1,num2) {if(Num1 <num2) {       return-1; }Else if(Num1 >num2) {       return1; }Else{       return0; }}vararr = [12,5,43,252,3];console.log (Arr.sort (fun))//Output [3, 5, A, 252]//If you need to make a descending order, simply swap the return value

(9) reverse (): Reverses the order of the elements in the array

var arr = ["A", "B", 2, "F"]arr.reverse (); Console.log (arr)    // output ["F", 2, "B" , "a"]

() concat (): Creates a copy of the original array, and can add parameters, parameters are added to the end of the copy, and the original array will not have any changes

var arr = ["A", "B", 2, "F"]var arrcopy = arr.concat () console.log (arrcopy)      Output ["A", "B", 2, "F"], equivalent to copying the original array var arrCopy1 = arr.concat ("Hello", "haha") console.log ( ARRCOPY1)   // Output ["A", "B", 2, "F", "hello", "haha"]console,log (arr)      // output original array, no change

(one) *slice (): Intercept, create a copy of the original array, you can add parameters, parameters need to be numbers, numbers indicate subscript, the subscript from one number to the next end of another number (note: Not including the end of the subscript)

vararr = ["A", "B", 2, "F", "Ha"]        //0 1 2) 3 4//pass a parameter 1, which means intercept starting from 1 (including 1)varArrcopy = Arr.slice (1) Console.log (arrcopy)//output ["B", 2, "F", "ha"]//Pass two parameters, indicating that the intercept starts at 1 and ends with 4 (including 1, but excluding 4)varArrCopy1 = Arr.slice (1,4) Console.log (arrCopy1)//output ["B", 2, "F"]//When the passed parameter is negative, the number of the position is replaced by the negative value plus the length of the array.varArrCopy2 = Arr.slice (1,-1) Console.log (arrCopy2)//output ["B", 2, "F"]//the array has a length value of 5,-1+5=4, so it remains truncated from 1 to 4 (excluding 4)

*splice (): This is an important array method that you can add, replace, or delete elements to an array

Delete: You can delete any number of elements, specify 2 parameters: (The specified position, the number of elements to delete), and if there is no second argument, all elements will be deleted after the specified position.

var arr = [1,3,5,7,9,11]; var = Arr.splice (arrcopy); // Delete 2 elements from 1 position Console.log (arr)    // Output [1, 7, 9, one]

Insert: You can insert any number of elements into the specified position, specifying 3 parameters: (The specified position, the number of elements to be deleted, the element to be added)

var arr = [1,3,5,7,9,11]; var arrcopy = Arr.splice (1,2,4, "6"); // Delete 2 elements from 1 position, add 4 and "6"Console.log (arr)    // Output [1, 4, "6", 7, 9, one]

(+) indexOf () and lastIndexOf ():

IndexOf: Finds the position of the element in the array starting with the first character of the array, specifying 2 parameters: (the element to find, where to start finding (optional))

var arr1 = [1,3,5,11,7,9,11];console.log (Arr1.indexof (one))      // output position 3 Console.log (Arr1.indexof (11,4))    // output position 6, the search is retrieved from the 4th position start

LastIndexOf: Finds the position of the element in the array starting at the end of the array, specifying the same parameters as IndexOf: (the element to find, where to start looking (optional))

var arr1 = [1,3,5,11,7,9,11];console.log (Arr1.lastindexof (one))      // output Position 6 

map (): Processes each element of an array by specifying a function and returns it as an array

// the squares of the elements in the following array are evaluated var arr = [1,2,3,4,5]var arr2 = Arr.map (function(num) {     return num*num;}); Console.log (arr2)   // Output [1, 4, 9, +]

( every): Determines whether each element in the array satisfies a given condition and returns true only if all elements satisfy the condition

var arr = [1,2,3,4,5]; var arr3 = Arr.every (function(x) {     return x < 8;}) Console.log (ARR3)     // output True// returns False when any element does not meet the criteria

(+) filter (): Filter function, which handles each element of an array by specifying a function, and finally returns an array that satisfies the filter condition

// finds elements greater than 15 in the following array var arr = [11,22,13,24,15]; var arr4 = Arr.filter (function(x) {     return x >;}) Console.log (ARR4)      // output [up]

3. Class Array (pseudo-array):

Definition: An array of classes is essentially an object, but you can use the attributes of the object and data to emulate the arrays and must contain the length property, as an example:

var obj = {    0: "A",    1: "B",    2:8,    3: "C",     4,    Push:Array.prototype.push,   // This class array has the push method }        Obj.push ("D")       // Add a "D"    Console.log (obj.length) at the end of the array     the length of the output at this time is 5, indicating a successful addition

The class array is converted to arrays as an example of the above code:

var obj1 = Array.prototype.slice.call (obj) console.log (obj1)    // output Array ["A", "B", 8, " C "]

* Here is a question about an array of classes:

varobj = {     "2": "A",         "3": "B",          "Length": 2,     "Push": Array.prototype.push}obj.push (C); Obj.push ("D");//Q. What is the last output of this console.log (obj)? //Answer://"2": "A",--equal to "0": "A"//"3": "B"--equals "1": "B"//push ("C")--equals "2": "C"//push ("D")--equals "3": "D"//so the last added "C" and "D" will overwrite the values of the previous "a" and "B", the value of length is 4

JavaScript Base-----Arrays (Array)

Related Article

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.