Object and array reference type-JavaScript tips-js tutorial

Source: Internet
Author: User
This article will share with you the object and array reference types in my javascript advanced programming learning notes, involving knowledge about javascript reference types, if you are interested in the javascript reference type, refer to this article to share with you the object and array reference types in my javascript advanced programming learning notes, involving knowledge about the javascript reference type, let's take a look.

1. Object Type

Most reference type values are Object-type instances, and objects are the most commonly used types in ECMAScript.

There are two ways to create an Object instance:

The new operator is followed by the Object constructor:

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

Representation of object literal:

  var person={     name:"webb",     age:25   };

2. Array type

In addition to objects, the Array type is probably the most common type in ECMAScript.
Each item of the ECMAScript array can save any type of data (for example, the first position can store strings, the second position can store values, the third position can store objects, and so on ). In addition, the size of the ECMAScript array can be dynamically adjusted, that is, it can automatically increase as data is added to accommodate new data.

There are two basic ways to create an array,

Use the Array constructor:

Var colors = new Array (); var colors = new Array (20); // You can also set the length attribute var colors = new Array ("red", "blue ", "green"); // Array containing three strings var colors = Array (3); // the new operator can be omitted.

Array literal representation

Var colors = ["red", "blue", "green"]; alert (colors [0]); // display the first colors [2] = "black "; // modify the third item colors [3] = "brown"; // Add the fourth item

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

Var colors = ["red", "blue", "green"]; colors. length = 2; alert (colors [2]); // undefined colors [colors. length] = "black"; // Add an item at the end

2.1 detection array

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

If (value instanceof Array) {// perform some operations on the Array}

The problem with the instanceof operator is that it assumes that there is only one global execution environment. If the webpage contains multiple frameworks, there are actually two or more different global execution environments, so there are two or more different versions of the Array constructor. If you input an array from a framework to another framework, the input array and the array originally created in the second framework have different constructors respectively.

To solve this problem, the Array. isArray () method is added to ECMAScript5. The purpose of this method is to determine whether a value is an array or not, no matter which global execution environment it creates,

If (Array. isArray (value) {// perform some operations on the Array}

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

2.2 Conversion Method

The toString () method of the array is called to return a comma-separated string consisting of each value in the array. The returned value of () is an array. In fact, to create this string, the toString () method of each item in the array is called. 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 value as the toString () and valueOf () methods, but not always. When the toLocaleString () method of the array is called, it also creates a comma-separated string of array values. The only difference from the first two methods is that, in order to obtain the value of each item, the toLocaleString () method of each item is called, rather than 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 can use the join () method to output arrays and specify separators. The default Delimiter is comma: var colors = ["red ", "blue", "green"]; alert (colors. join (","); // red, blue, green alert (colors. join ("|"); // red | blue | green

2.3 stack method (LIFO)

Push (): accept any number of parameters, add them one by one to the end of the array, and return the length of the modified array;
Pop (): removes the last entry 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 (): remove the first entry of the array and return the item. At the same time, the length of the array is reduced by 1;
Unshift (): As the name suggests, it is opposite to shift (). It can add any item at the front end of the array and return the length of the array.

2.5 re-sorting method

Reverse (): reverse the order of array items;

Sort (): sort in ascending order by default. To achieve sorting, the sort () method calls the toString () method of each item and then compares the obtained string to determine how to sort it. Even if each item is a numerical value, the comparison is a string, as shown below.

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

This sorting method is not the best solution in many cases. Therefore, the sort () method can accept a comparison function as a parameter to specify which value is located before which value.

Function compare (value1, value2) {if (value1
 
  
Value2) {return 1 ;}else {return 0 ;}}
 

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


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

2.6 Operation Method

Concat (): Creates a new array based on all 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. It is mainly used to insert an entry into the middle of the array, but there are two ways to use this method.

Delete: You can delete any number of items. You only need to specify two parameters: the location of the first item to be deleted and the number of items to be deleted.

Insert: you can insert any number of items to a specified position. You only need to provide three parameters: Start position, 0 (number of items to be deleted), and the item to be inserted. If you want to insert multiple items, you can upload the fourth, fifth, or any number of items. For example, splice (, "red", "green ") the string "red" and "green" will be inserted from position 2 of the current array ".

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

2.7 Location Method

IndexOf () and lastIndexOf (): both methods accept two parameters: the item to be searched and (optional) The index at the start point. The former searches backward from the beginning, and the latter searches forward from the end.

2.8 Iteration Method

ECMAScript5 defines five Iteration Methods for arrays. Each method accepts two parameters: the function to run on each item and (optional) the scope object that runs the function -- the value that affects this. The function passed in these methods will receive three parameters: the value of the array item, the position of the item in the array, and the array object itself.

Every (): run the given function for each item in the array. If this function returns true for each item, true is returned.
Filter (): If you run a given function for each item in the array, returning this function returns an array consisting of true items.
ForEach (): To run a given function for each item in the array, this method has no return value.
Map (): runs a given function for each item in the array and returns an array composed of the results of each function call.
Some (): run the given function for each item in the array. If this function returns true for any item, true is returned.

The preceding methods do not 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 (): starts from the first entry of the array and traverses it one by one to the end;
ReduceRight (): starts from the last entry of the array and traverses forward to the first entry.
Both methods accept two parameters: a function called on each item and (optional) the initial value of the basic value of merging. The function passed to these methods accepts four 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 to the next item as the first parameter. 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.