javascript--Array of reference types

Source: Internet
Author: User
Tags array sort javascript array


Before this dish was intended to write a reference type object after writing the base type, because object is the basis of a reference type, and other reference types are also based on object. Just the basic understanding of the object and simple operation does not write much, and is intended to be written along with the prototype, prototype chain. Benbow will introduce the reference type array, which is the array in JavaScript.


What is the array in the first place? An array is a linearly allocated memory that computes offsets and accesses the elements in an integer. Unfortunately, this definition refers to arrays in other languages, and there is no such data structure in JavaScript. Instead, JavaScript creates a structure of an array of classes based on an object, which converts the subscript of an array into a string as a property. This structure is less efficient than a real array, but it is more convenient, flexible, and powerful. The array type of JavaScript is also the most used other than object.


There are two ways to declare an array of javascript:

1.Array () constructor

2. Array literals

Array () constructor

Use the new operator to invoke the array constructor to complete the instantiation of the array.

var New Array ();

You can also pass in parameters when you create a new array using the array () constructor, in the following ways:

1). One parameter

When the passed-in parameter is a numeric value, a length property is generated as an array of values.

When the parameter passed in is not a numeric value, an array containing the value with length 1 is generated.

2). Multiple parameters

Generates an array that contains all the parameter values.

var New // []    new//["3"]    new//["Red", "green", "blue "]//3//1//3

In particular, it is important to note that I do not simply say length as "lengths" because the length property of the JavaScript array should not be fully understood as "length", which I will explain later.

array literal
var arr = [1,3,5,7,9];

This form of affirmation is also the most commonly used, and its writing method is more concise and intuitive.


What is the character of the array of JavaScript, or is it different from an array of other languages?

1. Most specifically, each item of a JavaScript array can hold a different data type.

var myarr = [1, "Hello",null, undefined,{"age": "Lily"},false

So it seems that the JavaScript array is really powerful, not only that it can hold different types of values, but also that the type of each item in the same array can be different.

You can also modify the entries in the array by using the subscript index

// [1, "Hello", null, "XXX", Object,false]

The length property of a 2.JavaScript array is dynamically variable, including implicit and explicit changes.

Implicit is the "brace large" array by adding values to the array, and explicitly setting the length property of the array directly. Due to the special length property, the next step is described in detail.

Length Property

Since arrays in JavaScript are created based on objects, length does not entirely represent its length and should be understood as an attribute of the array object. How to understand it, examples are as follows.

I printed the previously declared array Myarr on the console:

We can clearly see that the array is the object, the so-called index subscript is actually a property in the object, but these properties are named after a continuous number. Looking down, we see the length property tied to the indexed property, and the object-specific _proto_ property (which is closely related to the prototype of the object, which we'll discuss later).

The array we can even simply understand to create the following objects:

var myarr = {      "0": 1,      "1": "Hello",      null,       "3": Undefined,      "4": {"Age": "Lily"},      false,      "Length": 6      .      .}    

Would anyone say it makes sense to discuss it? The length value does represent the array lengths. Let's discuss this problem by understanding how to explicitly change the length value.

The length property of the JavaScript array is not read-only, and when we change the length to an hour, the extra items are automatically truncated.

Myarr.length = 3//[1, "Hello", null]

When we set the length value to large, the answer to the previous question is on the horizon.

myarr.length = 100;

As we can see from the result graph, although we increase the length value to 100, the displayed array still has only 6 items initialized, and it changes only one of the property values of the "object" of the array.

Look at an example, if we initialize an empty array and then increase its property value:

var New  = 100;

You can see that even if you increase the length property, it is still an empty array.

As we have said in the JavaScript Advanced program, uninitialized items are automatically populated with undefined values when we make the values of the arrays larger. What does it mean?

var = [myArr2 = 5//pseudo [1,2,3,undefined,undefined]// undefined

It means that when the length property increases, the number of items in the array increases at the same time, except that the contents of the increment are undefined values. But from the above two examples we can see that this is not the case, index subscript does not increase, only change the value of the length property.

When you perform the fourth line of code in the previous example to print the fourth item in the MYARR2 array, the result is undefined. This does not mean that the fourth item preserves the undefined value, but does not have a fourth item at all. Recall that when we retrieve a property that does not exist in an object, is the returned undefined? That's the truth!

So what do we certify so much for?

1. The subscript of an array does not increment with the size of the length property.

2. Because subscript is the attribute, they are likely to be discontinuous when there is human intervention!

Understand the above two points, is to use after the array built-in methods to reduce the occurrence of errors. I was also looking at the example of a great God blog, and after understanding it I reminded myself that the length of the array is not exactly the same thing.

Common Methods

Because of the many methods of JavaScript arrays, we try to introduce them in the most concise language.


There are two ways to detect if a variable is not an array:

1. Theinstanceof operator, which is used to detect which instance of the reference type the value is.

var arr = [instanceof],    //true

2.Array.isarray () method. Because the instanceof operator assumes a single global environment, this method is ECMAScript5 to accommodate multiple windows.

var arr = [All-in    -all],=//true
Join () method

Makes a connection character with the specified character, joins the items in the array in turn, and returns the composed string. When you do not pass in parameters or pass in parameters as undefined, "," stitching.

var colorarr = ["Red", "green", "Blue"//red,green,blue//Red , Green,blue//red*green*blue
stack and Queue methods

First say the Stack method, "LIFO". The push () method adds several items to the end of the array and returns the new arrays length, and thepop () method extracts an item from the end of the array and returns the item that was fetched.

var colorarr = ["Yellow", "orange"],    = Colorarr.push ("White", "Black"//  4var item =//black

Team column method, "FIFO". The shift () method extracts an item from the beginning of the array and returns the item. The queue operation of the array can be implemented with the push () method.

var colorarr = ["Yellow", "orange"],    = Colorarr.push ("White", "Black"//4  var item =//Yellow

The unshift () method is similar to the push () method. Just add several items from the beginning of the array and return the new array length. With the Pop () method, you can implement the array's reverse queue operation. The Unshift () method is less efficient than the other methods in the array, so it is prudent to use it in practice.

var colorarr = ["Yellow", "orange"],    = Colorarr.unshift ("Red", "green", "Blue"//  5var item =//Orange

How do you remember the return values of these methods in the stack and queue methods? A little trick, if you are adding an item to an array, returns the length of the new array. If you are fetching an item from an array, the item returned is the one that was fetched. Isn't it good to remember?

Sorting Methods

The reverse () method, which reverses the array sort. Intuitive but not enough milk flexible.

var numarr = [1,2,3,4,5,6//6,5,4,3,2,1

The sort () method, which is used to arrange arrays in some order, such as increment or decrement.

var numarr = [1,22,3,2,26//1,2,22,26,3

From the example above, the sort () method is not sorted as we expected, because the sort () method, by default, is the ToString () method of calling each item in the array, which means that the actual comparison is not a number but a string, so the desired result is not obtained.

In order for it to be sorted as expected, the comparison function needs to be passed in:

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

A comparison function receives two parameters. The comparison rules are probably as follows: When you want value1 to return a negative number before value2, you want the value1 to return a positive number after value2, and return 0 for equality.

var numarr = [1,22,3,2,26//1,2,3,22,26

The comparison function above can compare most data types, and if you want to compare only numeric values, you can use a simplified version of the comparison function.

function compares (value1, value2) {  return value1- value2;          }    

Of course, all of the above examples are in ascending order, in descending order, only two parameters in the function can be swapped.

Operation Method

There are three main methods for manipulating arrays,splice (),concat () , and Slice () methods. Let's first introduce the next splice () method, because it should be considered the most powerful array method.

Splice (A,B,C) receives three parameters, a represents the position where the action was performed, b represents the number of times the delete operation was performed at the action location, and C represents the value that needs to be inserted into the operation, which can be multiple, and the return value is the deleted array item. The operation of three kinds of arrays can be derived according to the a,b,c three parameters.


var namearr = ["Tom", "Lily", "Sam", "Bill"],    = Namearr.splice (+//  Tom,bill//Lily,sam

Omitting the parameter c is the delete operation for the array. But here to notice how to delete this process, first found in the array of position 1, "Lily", when a delete operation was originally located in position 2 of the "Sam" to a position 1, and then perform a second delete operation. Understanding this process makes it easier to understand the insertion and replacement methods.

Insert :

Item = Namearr.splice (1,0, "Kobe", "James"//Tom,kobe,james,bill// empty array

The parameter b is 0, that is, no delete operation is performed on position 1, only "Kobe", "James" are inserted.


Item = Namearr.splice (2,2, "Fanfan"//Tom,kobe,fanfan//James,bill

Remove and return "James", "Bill", and then add "Fanfan" to position 2 by deleting the two delete operations first.

When you fully understand the splice () method, you can think of it as an operation. Divided into three kinds is just easy to understand.

The concat () method, which is used to create a new array based on the current array. The simple thing is to first create a copy of the original array, and then add the received parameters to the end of the array and return the new array.

var arr = [Arr.concat    ], = ([4,5]    ),= Arr.concat (6,7)    , = Arr.concat (8,[9,10//* * *//1,2,3,4,5//  1,2,3,6,7//1,2,3,8,9,10

As you can see from the above example, the incoming parameters can be stitched into a new array, whether they are individual values or arrays or both.

The Slice () method creates a new sub-array based on several items in the current array. Receives two parameters, the first argument is the start position, and the second parameter is the end position. Returns an array of the previous items from the starting position to the end position, or to the end of the array if the end bit is not specified.

var arr = [1,2,3,4,5,6,7,8,9,10],    = Arr.slice (3),    = Arr.slice (3,8//  1,2,3,4,5,6,7,8,9,10//4,5,6,7,8,9,10//4,5,6,7,8
Thank you for your visit and hope to be of help to you.

javascript--Array of reference types

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: 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.