JavaScript Advanced Programming Learning Notes object and array reference type _javascript tips

Source: Internet
Author: User
Tags array length prev

This article to share my JavaScript advanced programming Learning notes of the object and array reference types, related to JavaScript reference type knowledge, we look at it together.

1. Object type

Most reference type values are instances of type object, and object is one of the most used types in ECMAScript.

There are two ways to create an instance of object:

The new operator is followed by the object constructor:

   var person=new Object ();
   Person.name= "Webb";
   person.age=25;

Object literal notation:

  var person={
     Name: "Webb",
     age:25
   };

2. Array type

In addition to object, the array type is probably the most commonly used type in ECMAScript.
Each item of the ECMAScript array can hold any type of data (for example, the first position can hold the string, the second position holds the value, the third position saves the object, and so on). And the size of the ECMAScript array can be dynamically adjusted, that is, it can grow automatically as the data is added to accommodate the new data.

There are two basic ways to create arrays.

Using the array constructor:

var colors=new Array ();
     var colors=new Array;   You can also set the Length property
     var colors=new Array ("Red", "Blue", "green");   An array containing 3 strings,
     var colors=array (3);   The new operator can be omitted

Array literal notation

 var colors=["Red", "Blue", "green"];
     Alert (colors[0]);   Show the first item
     colors[2]= "BLACK";   Modify the third item
     colors[3]= "Brown";   New Fourth item

Note: The length property of an array is characteristic-it is not read-only. So by setting this property, you can remove or add items from the end of the array. For example

     var colors=["Red", "Blue", "green"];
     colors.length=2;
     Alert (colors[2]);   Undefined
     colors[colors.length]= "black";   Add Item at end

2.1 Array of detections

For a Web page, or a global scope, you can use the instanceof operator to determine whether an object is an array:

   if (value instanceof Array) {
        //array performs certain actions
     }

The problem with the instanceof operator is that it assumes that there is only one global execution environment. If a Web page contains more than one frame, there is actually more than two different global execution environments, so there are more than two different versions of the array constructor. If you pass an array to another frame from one frame, the passed-in array has its own different constructors than the array created in the second frame.

To solve this problem, ECMAScript5 added the Array.isarray () method. The purpose of this method is to ultimately determine whether a value is an array, regardless of the global execution environment in which it was created.

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

Browsers that support this method are ie9+, Firefox 4+, Safari 5+, Opera 10.5+, and Chrome.

2.2 Conversion Methods

The call to the ToString () method of the array returns a comma-delimited string of strings of each value in the array. And the call to ValueOf () returns an array. In fact, in order to create this string, the ToString () method for each item of the array is invoked. For example

var colors=["Red", "Blue", "green"];
     Alert (colors.tostring ());   Red,blue,green
     alert (colors.valueof ());   Red,blue,green
     alert (colors);   Red,blue,green

In addition, the tolocalestring () method often returns the same values as the ToString () and valueof () methods, but not always. When the toLocaleString () method of an array is invoked, it also creates a comma-delimited string of array values. The only difference from the first two methods is that this time, in order to get the value of each item, the toLocaleString () method for each item is invoked, not the ToString () method.

  var person1={
        tolocalestring:function () {return
          ' webbxx ';
        },
        tostring:function () {return
          " Webb ";
        }
     };
     var person2={
        tolocalestring:function () {return
          "Susanxx";
        },
        tostring:function () {
          return "Susan";
        }
     ;
     var people=[person1,person2];
     alert (people);   Webb,susan
     alert (people.tostring ());   Webb,susan
     alert (people.tolocalestring ());   Webbxx,susanxx
     uses the Join () method to output an array, and specifies the delimiter, which defaults to commas:
          var colors=["Red", "Blue", "green";
          Alert (Colors.join (","));   Red,blue,green
          alert (colors.join ("| |)");   red| | blue| | Green

2.3 Stack Method (LIFO)

Push (): Accepts any number of parameters, adds them to the end of the array one by one, and returns the length of the modified array;
Pop (): Removes the last item from the end of the array

  var colors=new Array ();
        var Count=colors.push ("Red", "green");
        alert (count);   2
        Count=colors.push ("Black");
        alert (count);   3
        var item=colors.pop ();
        alert (item);   "Black"
        alert (colors.length);   2

2.4 Queue Method (FIFO)

Shift (): Moves the first item of the divisor group and returns the item, while the array length is reduced by 1;
Unshift (): As the name suggests, in contrast to the shift (), you can add any item to the front of the array and return the length of the array.

2.5 reordering Methods

Reverse (): Reverses the order of the array items;

Sort (): By default in ascending order, for sorting, the sort () method invokes the ToString () method for each item, and then compares the resulting string to determine how to sort. Even if each item is a numeric value, the comparison is also a string, as shown below.

   var values=[0,1,5,10,15];
        Values.sort ();
        alert (values);   0,1,10,15,5

This sort of arrangement is not the best solution in many cases. So the sort () method can accept a comparison function as an argument to specify which value precedes which value.

 function Compare (value1,value2) {
        if (value1<value2) {
          return-1;   Value1 before value2
        }else if (value1>value2) {return
          1;
        } else{return
          0; 
        }
     

This comparison function can be applied to most types, as long as it is passed as a parameter to the sort () method, as follows,


 var values=[0,1,5,10,15];
        Values.sort (compare);
        alert (values);   0,1,5,10,15

2.6 Method of Operation

Concat (): Creates a new array based on all the items in the current array. For example

 var colors=["Red", "Blue", "green"];
        var colors2=colors.concat ("Yellow", ["Black", "Brown"]);
        alert (colors);   Red,blue,green
        alert (colors2);   Red,blue,green,yellow,black,brown

Slice (): Creates a new array based on one or more items in the current array. For example

       var colors=["Red", "green", "blue", "yellow", "purple"];
        var colors2=colors.slice (1);   Green,blue,yellow,purple
        var colors3=colors.slice (1,3);   Green,blue,yellow

Splice (): This method is probably the most powerful array method, the main purpose is to insert the item to the middle of the array, but the way to use this method is as follows 2 kinds.

Delete: You can delete any number of items by specifying only 2 parameters: the position of the first item to delete and the number of items to delete.

Insert: You can insert any number of items to a specified location by providing only 3 parameters: Start position, 0 (number of items to delete), and items to insert. If you want to insert more than one item, you can transfer four or five to any number of items; For example, splice (2,0, "Red", "green") inserts the string "Red" and "green" from the current array's position 2.

The splice () method always returns an array containing the items that were deleted from the original array (an empty array is returned if no items are deleted).

2.7-Position method

IndexOf () and LastIndexOf (): Both methods accept two parameters: the Xiang (optional) To find indicates the index at which to find the start position. The former starts with a backward lookup from the beginning, and the latter looks forward from the end

2.8 Iterative Methods

ECMASCRIPT5 defines 5 iteration methods, each of which accepts 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 into these methods receive three parameters: 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, and returns True if the function returns true for each item.
Filter (): Each item in an array runs the given function, returning an array of items that the function returns True.
ForEach (): Runs the given function for each item in an array, and this method has no return value.
Map (): Each item in an array runs the given function, returning an array of the results of each function call.
Some (): Runs the given function for each item in the array, and returns True if the function returns true for either item.

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

var numbers=[1,2,3,4,5,4,3,2,1];
        var everyresult=numbers.every (function (item,index,array) {return
          item>2;
        });
        alert (everyresult);   False
        var someresult=numbers.every (function (item,index,array) {return
          item>2;
        });
        alert (someresult);   True
        var filterresult=numbers.every (function (item,index,array) {return
          item>2;
        });
        alert (filterresult);   [3,4,5,4,3]
        var mapresult=numbers.every (function (item,index,array) {return
          item*2;
        });
        alert (mapresult);   [2,4,6,8,10,8,6,4,2]

2.9 Merge Method

Reduce (): begins with the first item of the array, traversing to the last;
Reduceright (): Begins with the last item of the array and traverses forward to the first item.
Both methods accept two parameters: a function called on each item and (optionally) an initial value that is the base of the merge. The functions passed to these methods accept 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 passed as the first argument to the next. For example

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

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.