JS Basic Knowledge Review: Reference type (i)

Source: Internet
Author: User
Tags alphanumeric characters

In ECMAScript, a reference type is a data structure used to organize data and functionality together, while an object references an instance of a type.

Although ECMAScript is technically an object-oriented language, it does not have the basic structure of classes and interfaces supported by traditional object-oriented languages, so although reference types and classes seem to want to die, they are not the same concept.

However, reference types can sometimes be called object definitions because they describe the properties and methods that a class of objects have.

The new object is implemented with a constructor, which is itself a function, except that the function is defined for the purpose of creating a new object.

ECMAScript provides a number of native reference types that developers can use to implement common computing tasks.

Object is the most used type in ECMAScript, and although instances of object do not have much functionality, they are really ideal for storing and transmitting data in an application.

There are two ways to create an object instance:

Use the new operator followed by the object constructor, for example: Var person=new object ();p erson.name= "name";p erson.age=29;

You can also use object literal notation, and it is important to note that when you represent an object using object literal notation, you cannot add a comma after the last property, otherwise it will cause errors in IE7 and earlier versions and opera.

Object literals are shorthand for object definitions to simplify the process of creating objects that contain a large number of attributes, such as: Var person={name: "Name", age:29};

When using object literal syntax, a property name can use either a string or a number, but the numeric attribute name is automatically converted to a string, for example: Var person={"name": "Name", "Age": 29,5=true}

When using object literal syntax, if you leave the curly braces blank, you can define an object that contains the default properties and methods, for example: Var person={};//is the same as new object () person.name= "name";p erson.age=29;

When you define an object by object literal, you do not actually call the object constructor (Firefox2 and previous versions are called, but not after Firefox3).

In practice, people tend to be more inclined to use object literal syntax, because this syntax requires less code and can give people the feeling of encapsulating data.

Object literals are also the preferred way to pass a large number of optional parameters to a function, such as:

function DisplayInfo (args) {

var output= "";

if (typeof args.name== "string") {output+= "name:" +args.name+ "\ n";}

if (typeof args.age== "number") {output+= "Age:" +args.age+ "\ n";}

alert (output);

}

DisplayInfo ({name: "Nicholas", age:29});

DisplayInfo ({name: "Greg"});

In general, object properties are accessed using dot notation, but in JavaScript you can also use square brackets to represent properties that access objects, such as:

alert (person.name);//"Nicholas" (point notation is recommended unless you must use a variable to access the property)

Alert (person["name"]);//"Nicholas" (square brackets notation can write property names in square brackets)

Alert (Person[propertyname]);//"Nicholas" (square brackets notation can also write variable names in square brackets)

person["First Name"]= "Nicholas"; (The dot notation is used when there are non-alphanumeric characters such as spaces in the attribute name, so it is best to use square brackets notation)

The array type is used in ECMAScript to represent an array, and unlike other languages, each item of the ECMAScript array can hold any type of data, and the size of the array can be dynamically adjusted.

There are two basic ways to create an array:

The first way is to use the array constructor, for example: Var colors=new Array ();

If you know the length of the array beforehand, you can also pass the number to the constructor, which automatically becomes the value of the length property of the array, for example: Var colors=new array (20);

You can also pass the items that should be included in the array like the array constructor, for example: Var colors=new array ("Red", "Blue", "green");

When a value is passed only to the constructor, if the value is a number, an array containing the number of given items is created according to that number, and if a parameter of another type is passed in, an array of only one item that contains that value is created.

You can also omit the new operator when creating an Array constructor, for example: Var colors=array (3), Var names=array ("Greg");

The second way is to use the array literal notation, where the array literal is represented by a pair of square brackets containing the array items, separated by commas between the multiple array items, for example:

var colors=["Red", "Blue", "green"];//create an array with three strings

var names=[];//create an empty array

var values=[1,2,]//is not recommended, and the IE8 and previous versions will create an array of three items per item with a value of 1,2,undefined, and other browsers will create an array containing 1, 22 items

var options=[,,,,,]//is not recommended, and an array of six undefined will be created in IE8 and previous versions, and an array with five undefined will be created in other browsers

Because the processing of IE differs from other browsers, it is recommended that you do not use default values to create arrays.

As with objects, when you use array literal notation, the array constructor is not called (except for Firefox3 and previous versions).

When reading and setting the values of an array, use square brackets and provide a corresponding 0-based numeric index, for example:

var colors=["Red", "Blue", "green"];//create an array with three strings

var names=[];//create an empty array

Alert (colors[0]);//Display the first item (the value of the corresponding item is returned if the index is less than the number of items in the array)

Colors[2]= "BLACK";//Modify the third item

Colors[3]= "Brown";//new Item fourth (the index exceeds the number of existing items, the array is automatically incremented to the length of the index value plus 1)

alert (colors.length);//3 (in the initial case, there are three values in the array)

alert (names.length);//0

The Colors.length=2;//length property is not read-only, and the length property allows you to remove items from the end of the array

Alert (colors[2]);//undifined

The Colors.length=4;//length property is not read-only, and you can add items to the end of the array by using the Length property

Alert (colors[3]);//undifined (added undefined value for each entry)

Colors[colors.length]= "BLACK";//Add a color at position 4 (the index of the last item in the array is always length-1, so the position of the next new item is length)

Colors[colors.length]= "Brown";//Add another color at position 5 (each time an item is added at the end of the array, its Length property is automatically updated to reflect this change)

Colors[99]= "Pink"; When you place a value above the current array size, the array recalculates its length value

alert (colors.length);//100 (length equals last item's index plus 1)

An array can contain up to 4294967295 items of data, and if you want to add more items than this upper limit, an exception occurs, and creating an array with an initial size close to this upper value may result in a script error that runs for an unusually long time.

Determines whether an object is an array that can be implemented using the instanceof operator, for example: if (value instanceof Array) {//Some operations}

However, since the instanceof operator assumes that there is only one global execution environment, if the page contains more than one frame, there are actually more than two different global execution environments, and there are more than two different versions of the array constructors. If a parameter is passed to another frame from one frame, the incoming array has a different constructor than the array that was created natively in the second frame.

To solve this problem ECMAScript5 has added the Array.isarray () method, which is designed to ultimately determine whether a value is an array, regardless of which global execution environment it was created in, for example: if (Array.isarray (value) ) {//Some actions}

Browsers that support this approach are ie9+, firefox4+, safari5+, opera10.5+, and Chrome.

Each object has the toLocaleString (), toString (), and ValueOf () methods, which, by default, return array items as a comma-delimited string of three methods.

var colors=["Red", "Blue", "green"];//create an array with three strings

Alert (colors.tostring ());//red,blue,green (the Call to the ToString () method returns a comma-delimited string of strings for each value in the array)

Alert (colors.valueof ());//red,blue,green (call ValueOf () method returns an array)

alert (colors);//red,blue,green (pass the array directly to alert (), because alert () receives the string argument, it calls the ToString () method in the background to get the same result as ToString ()

When the toLocaleString () method is called, a comma-delimited string of array values is also created, unlike the first two methods, which, in order to get the value of each item, is called the toLocaleString () method for each item.

var person1={tolocalestring:function () {return "Nikolaos";},tostring:function () {return "Nikolaos";}};

var person2={tolocalestring:function () {return "Grigorios";},tostring:function () {return "Greg";}};

var people=[person1,person2];

alert (people);//nikolaos,greg

Alert (people.tostring ());//nikolaos,greg

Alert (people.tolocalestring ());//nikolaos,gigorios

If you use the Join () method, you can construct an array string with a different delimiter, the join () method value takes a string as a delimiter as a parameter, and then returns a string containing all the array items.

var color=["Red", "green", "blue";

Alert (Colors.join (","));//red,green,blue

Alert (Colors.join ("| |)"); /red| | green| | Blue

If you do not pass any value to the join () method or pass in undefined, use a comma as the delimiter, and IE7 and earlier will incorrectly use the string "undefined" as the delimiter.

If the value of an item in the array is null or undefined, the value is represented as an empty string in the returned results of the four methods above.

The ECMAScript array also provides a way for the array to behave like other data structures.

The stack is a LIFO (Last-in-first-out, LIFO) data structure, while the insert (called Push-in) and remove (called eject) values of items in the stack occur at the top of the stack.

The ECMAScript provides the push () and Pop () methods for implementing a stack-like behavior.

The push () method can accept any number of arguments, add them one at a to the end of the array, and finally 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 finally returns the item that was removed.

var colors=new array ();//Create an array

var Count=colors.push ("Red", "green");//push in two

alert (count);//2

Count=colors.push ("Black");//Push in another

alert (count);//3

var item=colors.pop ();//Get the last one

alert (item);//"BLACK"

alert (colors.length);//2

A queue is a FIFO (First-in-first-out, FIFO) data structure in which the queue adds items at the end of the list and removes items from the front end of the list.

The shift () method is provided in ECMAScript, which moves the first item in the array and returns the item, minus 1 of the item in the arrays.

Using the shift () and push () methods together, you can use arrays as you would with queues.

var colors=new array ();//Create an array

var Count=colors.push ("Red", "green", "Black");//push in three items

alert (count);//3

var item=colors.shift ();//Get the first item

alert (item);//"Red"

alert (colors.length);//2

The Unshift () method is also available in ECMAScript, which allows you to add any item to the front of the array and return the length of the new array.

Using the Unshift () and Pop () methods together, you can simulate the queue in the opposite direction.

var colors=new array ();//Create an array

var count=colors.unshift ("Red", "green");//push in two

alert (count);//2

Count=colors.unshift ("Black");//Push in another

alert (count);//3

var item=colors.pop ();//Get the last one

alert (item);//"Green"

alert (colors.length);//2

IE7 and earlier versions there is a bias in the implementation of JavaScript, where the Unshift () method always returns undefined instead of the new length of the array, IE8 returns the correct length value in compatibility mode.

The array in the ECMAScript has two reordering methods: reverse () and sort (), all of which are returned by the sorted array.

The reverse () method reverses the order of the array items, for example: Var values=[1,2,3,4,5];values.reverse (); alert (values);//5,4,3,2,1

The sort () method arranges the array items in ascending order by default (the smallest is first and the largest is the last).

In order to implement sorting, the sort () method invokes the ToString () transformation method of each array item, and then compares the resulting string to determine how to sort, for example:

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

Because this sort method is not optimal in many cases, the sort () method can also receive a comparison function as an argument so that we define which value is in front of which value, for example:

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

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

You can also sort the descending order by reversing the return value in the comparison function.

For numeric types or for which the valueof () method returns an object type of numeric type, a simpler comparison function can be used: function compare (value1,value2) {return value2-value1;}

ECMAScript provides a number of ways to manipulate the items that should be included in the array.

The Concat () method can create a new array for all items in the current array.

This method creates a copy of the current array, adds the accepted parameters to the end of the copy, and returns the newly constructed array.

In the case where no arguments are passed to the concat () method, it simply assigns the current array and returns a copy.

If one or more arrays are passed to the concat () method, the method adds each item of the array to the result array.

If a value is passed to the concat () method instead of an array, the values are simply added to the end of the array.

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

var colors2=colors.concat ("Yellow", ["Black", "Brown"]);

alert (colors);//red,green,blue

alert (colors2);//red,green,blue,yellow,black,brown

The slice () method can create a new array based on one or more items in the current array.

The slice () method can receive one or two parameters, that is, the starting and ending positions of the item to be returned.

In the case of only one argument, the slice () method returns all items starting at the specified position of the parameter to the end of the current array.

If there are two parameters, the slice () method returns all items between the starting and ending positions but not the item that contains the end position.

If the slice () method has a negative number in its argument, the array length is used to determine the corresponding position.

If the end position in the passed argument is less than the start position, an empty array is returned.

var colors=["Red", "green", "blue", "yellow", "purple";

var colors2=colors.slice (1);

var colors3=colors.slice (1,4);

var colors4=colors.slice ( -2,-1);

var colors5=colors.slick (4,1);

alert (colors2);//green,blue,yellow,purple

alert (COLORS3);//green,blue,yellow

alert (COLORS4);//blue

alert (COLORS5);//null

The main purpose of the splice () method is to insert an item into the middle of the array, which has the following three rules:

(delete) If you pass two parameters to the method, that is, the position of the first item to be deleted and the number of items to be deleted, you can delete any number of items from the specified location;

(insert) If the method is passed three or more than three parameters, that is, the starting position, 0 (the number of items to be deleted), and the item to be inserted, you can insert any number of items to the specified location;

(replace) If you pass three parameters to the method, that is, the starting position, the number of items to delete, and any number of items to insert (the number of deletions and the number of insertions can be unequal), you can insert any number of items into the specified location and delete any number of items.

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

var removed=colors.splice (0,1);//Delete first item

alert (colors);//green,blue

alert (removed);//red

Removed=colors.splice (1,0, "Yellow", "orange");//Insert two items starting from position 1

alert (colors);//green,yellow,orange,blue

alert (removed);//Returns an empty array

Removed=colors.splice ("Red", "purple");//Delete an item starting at position 1 and insert two items

alert (colors);//green,red,purple,orange,blue

alert (removed);//yellow

ECMAScript5 adds two location methods to an array instance: IndexOf () and LastIndexOf ().

Both methods accept two parameters: the item to find and the index that represents the location of the lookup start (optional).

where the IndexOf () method looks backwards from the beginning of the array, and the LastIndexOf () method looks forward from the end of the array.

Both of these methods return the position of the item to find in the array, or return-1 if not found.

When comparing the first argument to each item in the array, the equality operator is used, and if there are multiple occurrences in the array, only the first position found is returned.

Browsers that support both methods are ie9+, firefox2+, safari3+, Opera9.5, and Chrome.

ECMASCRIPT5 defines 5 iterative methods for an array, each of which receives two parameters: the function to run on each item and the scope object that runs the function (optional, which affects the value of 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 group object itself.

The Every () method runs the given function for each item in the array, and returns True if the function returns true for each item.

The Some () method runs the given function for each item in the array, and returns True if the function returns true for either item.

The filter () method runs the given function for each item in the array, and returns a list of the items that the function returns True.

The map () method runs the given function for each item in the array, and returns a list of the results of each function call.

The ForEach () method runs the given function for each item in the array, and the method does not return a value.

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.some (function (Item,index,array) {return (ITEM>2);});

alert (someresult);//true

var filterresult=numbers.filter (function (Item,index,array) {return (ITEM>2);});

alert (Filterresult);//[3,4,5,4,3]

var mapresult=numbers.map (function (item,index,array) {return item*2;});

alert (Mapresult);//[2,4,6,8,10,8,6,4,2]

Numbers.foreach (function (Item,index,array) {//perform certain actions});

The ForEach () method simply runs the passed-in function for each item in the array, with no return value, essentially the same as using the For loop to iterate over the algebraic group

Browsers that support these methods are ie9+, firefox2+, safari3+, Opera9.5, and Chrome.

ECMAScript5 also added two ways to merge arrays: reduce () and reduceright ().

Both of these methods iterate over all the items of an algebraic group and then build a value that is ultimately returned.

where the reduce () method iterates from the first item of the array to the last, Reduceright () traverses the last item of the array forward to the first item.

Both methods accept two parameters: a function that is called on each item and an initial value that is the basis of the merge (optional).

The functions passed to both methods receive four parameters: the previous value, the current value, the index of the item, and the array object.

The value returned by this function is automatically passed to the next item as the first argument, and the first iteration occurs on the second item of the array.

Whichever of these two methods is used depends entirely on which head begins to iterate over the array, and they are identical for the first time.

var values=[1,2,3,4,5];

var sum=values.reduce (function (prev,cur,index,array) {return prev+cur;});

alert (sum);//15

var sum2=values.reduceright (function (prev,cur,index,array) {return prev+cur;});

alert (sum2);//15

Browsers that support both methods are ie9+, firefox2+, safari3+, Opera9.5, and Chrome.

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.