Object and array objects in JavaScript

Source: Internet
Author: User
Tags array sort

Reference type: is a data structure used to organize data and functionality together.

5.1 object--Object Type!

To create an object instance, the first method: Use the new operator followed by the object constructor

1 1 var person = new Object (), 2 2 person.name = "Zhang San"; 3 person.age = " ;";

The second method: The method of literal representation

var person = {      name = ' Zhang San ', age      = 3   };  Note: The property name can also use a string: "Name" = "Zhang San";  

5.2 Arrays Array type

Each item of the ECMAScript array can hold any type of data, and the size of the array can be dynamically adjusted.

To create an array:

The first method  is var arr = new Array ();//Create an array arrvar  colors = new Array (10);//Create an array of length 10 var  num = new Array (1, 2, 3);//Create an array of three items [1,2,3]//the second method array literal means var colors = ["Red", "Blue", "green"];var food= [];    An empty array var  sum =[1,2,];   It is best not to create an array that contains 2 or 3 items, IE8 and 3 items below. 

When reading and setting the value of an array, use square brackets and provide the corresponding value based on the 0 numeric index, and the number of items in the array is stored in its Length property!

var num = [3,4,12,35,68,1];alert (num[1]);   Show the second alert (num[0]);//Show First alert (num.length);//   6  

5.2.1 Detecting arrays

var value = []//ecmascript3  , this method assumes that there is only one global execution environment! if (value instanceof Array) {     //array to perform certain operations      }//ecmascript 5 new Array.isarray () method if(Array.isarray ( Value) {  //To perform certain operations on an array      }  

5.2.2 Conversion method

All objects have a tolocalstring (), ToString (), ValueOf () method, where the ToString () method of the call array returns a comma-delimited string of each string in the array that is worth concatenation. The valueof () returns an array. Where: Alert () to receive string arguments, so the ToString () method is called in the background!!

var colors = ["Red", "Blue", "Green"];alert (Colors.tostring ());  red,blue,greenalert (colors.valueof ());  red,blue,greenalert (colors);  red,blue,green  

The array inherits the toLocaleString (), toString (), and valueof () methods, which, by default, return an array in the form of a comma-delimited string!

The join () method reproduces the output of the ToString () method. Such as:

var colors = ["Red", "green", "blue"];

Alert (Colors.join (",")); Output Red,blue,green

Alert (Colors.join ("| |)"); Output red| | blue| | Green

5.2.3 Array method

  1. 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!
  2. The Pop () method removes the last item from the end of the array, reduces the length value of the array, and returns the item that was removed!
    var num =[3,4,5,1,2];    var count = Num.push (5,7,8,10); The length of the array returned after receiving the push method    alert (count);  9     var remove = Num.pop ();//Receive the removed item returned by the Pop method    alert (remove);  Ten
  3. The shift () method removes the item from the top of the array and returns the item!
  4. The Unshift () method adds any item from the top of the array and returns the length of the array!
    var  num = [];var count = num.unshift (0), alert (count), var remove = num.shift (), alert (remove); /c14> 
  5. The
  6. reverse () method reverses the order of the array items
     1 var values = [1,2,3,4,5 ];2 3 values.reverse ();//Reverse Array Sort 4 5 alert (values);  The 
    1. sort () method sorts the array items in ascending order-that is, the minimum value is at the front and the largest value is the last. (compare by string memory)! The
       var sum = [0,1,5,10,15 ];//sort () method invokes the ToString () transformation method for each array item, and then compares the string Sum.sort () to the Enlightenment, and the alert (NUM); 0,1,10,15,5 

       sort () receives a comparison function as a parameter. The comparison function receives two parameters, if one argument should precede the second, returns a negative number if equal returns 0, and returns a positive number if the first argument should be in the second one!

       function  Compare (value1, value2) {if (value1 <  value2) {return 1 ;} else if (value1 & Gt  value2) {return-1 ;} else  {return 0 ;}} var values = [0, 1, 5, ten, ];values.sort (Compare); alert (values);//15,10,5,1,0 

      //Simpler method

      var num = [0, 1, 5, 10, 15];
      Num.sort (A, b) {
      return a-A;
      });
      Alert (num);
         
  7. The
  8. concat () method can create a new array based on all the items in the current array, specifically, this method creates a copy of the current array and then adds the received parameters to the end of the copy!
    //Two arrays are combined into a new array var alpha =  [A,b,c];var numeric = [];var] alphanumeric = alpha.concat (numeric);//a, b,c,1,2,3//Three arrays and non-array values are combined into a new array var num1 = [];var num2 = [3,4 ];var num3 = [5,6 ];var nums = Num1.concat (n um2,num3,7 ); alert (nums);       

     

  9. The
  10. Splice () method is the most powerful array method, the main purpose is to insert items into the middle of the array, there are three kinds of parties,
    1, delete: You can delete any item, just specify 2 parameters: The position of the first item to delete and the number of items to delete
          For example, splice (0,2) deletes the first two entries in the array
    2, insert: You can insert any number of items to the specified location. Just provide 3 parameters: Start position, 0 (both items to delete       number) and items to insert, if you want to insert multiple items, you can pass in the IV, fifth and any number of items, such as           and Nbsp;splice (2,0, "Red", "green") will insert the string "red" and "green" starting at position 2 of the current array!
    3, replace: You can insert any number of items to the specified location and delete any number of items at the same time! Three parameters: The starting position, the number of items to be     deleted and any number of items to insert, such as splice (2,1, "Red", "green") will delete the current array position 2       items, and then from position 2 Start inserting the string "red" and "green" . The return value of the

    Splice consists of an array of deleted elements. If only one element is deleted, an array containing only one element is returned. If no element is deleted, an empty array is returned.

     

    var num = [1,2,3,4,,5,6,7];

    var removed = Num.splice (2,1,8,9,10);//delete 1 items from start position 2 and add 8,9,10 entry

    Console.log (num);  // [1, 2, 8, 9, 4, 7:5, 8:6, 9:7]

    Console.log (removed);//[3]

       
  11. IndexOf () and LastIndexOf () are the two positional methods that are added in ECMA 5, both of which receive two parameters: the item to find and the index that represents the starting point of the lookup. IndexOf () looks backwards from the array header, LASTINDEXOF () starts looking forward from the end of the array! and must be strictly equal!
    Return value: Returns the position of the item to find in the array, or 1 if not found;
    var numbers = [1,2,3,4,5,4,3,2,1];console.log (Numbers.indexof (4));//3console.log (Numbers.lastindexof (4));// 5console.log (Numbers.indexof (bis));   5console.log (Numbers.lastindexof (bis));   3console.log (Numbers.indexof (6));    -1
  12. Every (): Each item in an array is a given function that returns True if the function returns true for each item. Does not change the original array.
    var passed = [12,5,8,44,130];console.log (passed.every (function(item,index,array) {    return item>10 ;}));   Falsevar passed = [12,5,8,44,130];console.log (passed.every (function(item) {    return item>3  

  13. Filter (): Each item in an array runs the given function, and returns a list of items that are true of the function.
    var numbers = [1,2,3,4,5,4,3,2,1];var result = Numbers.filter (function(item) {    return item > 3;}); Console.log (result);  [4, 5, 4]  

  14. ForEach (): Runs the given function for each item in the array. No return value
    function logarrayelements (element,index,array) {    console.log ("a[" +index+ "]=" +Element);} [2,3,45,56].foreach (logarrayelements);//a[0]=2//a[1]=3//a[2]=45//a[3]=56  

  15. Mab (): Each item in an array runs the given function, returning an arrays of the results of each call.
    var numbers = [1,2,3,4,5,4,3,2,1];var mapresult = numbers.map (function(item, index, array) {return item * 2; }); alert (Mapresult); [2,4,6,8,10,8,6,4,2]  

  16. Some (): Runs the given function for each item in the array, and returns True if the function returns true for any of the entries.
    function Isbigenough (element, index, array) {  return (element >=);} var passed = [2, 5, 8, 1, 4].some (Isbigenough);//passed is falsepassed = [5, 8, 1, 4].some (Isbigenough);//PA Ssed is true   

  17. Reduce () and reduceright (), the method that merges an array, iterates over all the items of an algebraic group, and then constructs a final return value. Reduce () starts with the first item in the array, Reduceright () starts with the last item in the array, and iterates through each item!
    Receives two parameters: a function that is called on each item and (optionally) as the initial value for the merge base.
    The function receives four parameters: the previous value, the current value, the index of the item, and the object of the array! Any value returned by this function will be automatically passed to the next item as the first argument. The first iteration is sent on the second item of the array, so the first parameter is the first item of the array, and the second parameter 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;},10 ); Console.log (sum);    -

Note: In these methods, every (), filter (), ForEach (), map (), some () are all iterative methods 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. The functions passed in these methods receive three parameters: the value of the array item, the position of the item in the array, and the object itself!

In addition, there are some methods of ECMAScript (ES6) specification, will be added after learning!

Object and array objects in 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.