JavaScript Common Objects Array (1)

Source: Internet
Author: User

The array type is almost the most commonly used type in JavaScript. The concept of arrays in JavaScript is similar to that in Java,c, but there are two points to emphasize:

1. Each item in the array can be saved in a different data type. For example, the first item holds a string data, the second item holds a value, and so on.

2, the length of array arrays can be dynamically adjusted. That is, you can add new content to an array at any time.

    • The creation of an array object
    • Access to array objects, adding elements
    • The array object is converted to a string
    • Stack method and queue method of array object
    • How to sort array objects
Array object is created using the array constructor
var colors = new Array()  //创建一个空数组var colors = new Array(20)  //创建一个长度为20的数组var colors = new Array("red", "blue", "black")  //创建一个长度为3的数组,元素分别为red,blue,black
Use array literals
var colors = []  //创建一个空数组var colors = ["red", "blue", "black"]  //创建一个长度为3的数组,元素分别为red,blue,black
Access to array objects, adding elements

The array is accessed by subscript, modified, and added. It is important to note that the subscript starts at 0.

For example:

var colors = ["red", "blue", "black"];var col1 = colors[0];colors[2] = "gray";var col2 = colors[2];colors[5] = "white";var col3 = colors[4];var col4 = colors[5];

The above code first defines an array of length 3, with elements of Red,blue,black.

With the subscript access, the Cor1 value is "red".

On the third line, change the "black" to "gray" by using subscript access to modify color[2]. Col2 is "gray".

5 lines, directly colors[5] is assigned to "white", then the array length colors.length value is 6

COLORS[5] value is "white", the middle is not assigned the value of colors[3], colors[4] value is undefined. COLORS[5] is "white".

It is also necessary to note that the length property of an array object is not a read-only property, but rather a property that can be dynamically modified, for example, we change the length value of the above colors to 6:

colors.length = 6;

At this point, the array length changes to 6,colors[3]~colors[5] are undefined.

We can also easily add array elements by using the array length property and array access to start with the 0 subscript feature:

var colors = [];colors[length] = "red";colors[length] = "blue";
The array object is converted to a string

Each object has ToString (), tolocalestring (), and valueof () methods.

The ToString () method of an Array object returns a comma-delimited string as a string for each element of the array.

For example:

  var colors = ["red""blue""black"];  alert(colors.toString());

Will output:

red,blue,black

In fact, when you call the ToString () method of an array, the ToString () method of the element is automatically called when you get the string form of each element.

Let's take a look at some instructive code:

var obj1 = {    "hello world!",    function() {      return"MyToString";    }};var obj2 = {    "hello world!"};var obj = [obj1, obj2];alert(obj.toString());

Get the following output:

We see that the ToString () method for each element is automatically called in order to get the ToString string for the array object. It is then stitched together into a comma-delimited string. For the obj1 element, the ToString () method that we overridden is called, and Obj2 is the default ToString () method.

The toLocaleString () method of an Array object also converts each array element to a string, separated by commas and stitched together into a total string. Unlike the ToString () method, in order to get the string for each element, the toLocaleString () method of the element is called, and we modify the above code slightly:

var obj1 = {    "hello world!",    function() {      return"MyToString";    },    function() {      return"MyToLocaleString";    }};var obj2 = {    "hello world!"};var obj = [obj1, obj2];alert(obj.toLocaleString());

Get the following output:

Stack method and queue method of array object

We know that the stack is a "LIFO" data structure, and the queue is a "FIFO" data structure. JS to enable us to use array objects like stacks and queues, the following methods are available:

push()pop()shift()unshift()
Push () and pop () methods

The push (obj) method actually adds the element specified by the parameter obj at the end of the array, and returns the length of the array after the push.

The Pop () method essentially takes the "upper stack" element at the end of the array and then the array length minus 1, returning the topmost element taken out.

The encapsulation of these two operations allows us to use arrays just like stacks. For example:

  var colors = [];  //创建一个空栈  var i = colors.push("red""blue");  //将"red","blue"入栈,i为入栈后栈长,值为2  var col1 = colors.pop();  //出栈,返回栈顶元素"blue"
Shift () and push () methods

The push () method adds an element at the end of the array, where the shift () method extracts the element at the head of the array, minus 1 of the array length, returning the elements of the array header.

Working with push () and shift () allows us to manipulate array objects like the operations queue:

  var colors = [];  //创建一个空队列  var i = colors.push("red""blue");  //将"red","blue"加入队列,i为新队列长,值为2  var col1 = colors.shift();  //取出数组头部元素,此时col1值为"red"。colors.length值为1
Unshift () and Pop () methods

The role of Unshift (obj) is to add the element obj to the head of the array and return the length of the new array. Usage is similar to push (), which is used with pop () to use the array object as a reverse queue.

How to sort array objects

The sorting methods used in array are reverse () and the sort () method.

Reverse () method is simply to reverse the array elements, the scope of application is limited.

The sort () method uses the broader, default sort () method, which invokes the ToString () method of each element of the array, and then compares the resulting string, small in front, and large in the back. However, this approach has strong limitations, such as:

  var nums = [1, 2, 12, 4, 21];  nums.sort();

Convert each element of Nums to a string, get the string form of 1,2,12,4,21, and compare its string form to get the following sort result:

Comparing values as strings often does not get the result we want, so the sort () method can accept a comparison function as a parameter and then sort the array by comparison function. Rules for comparing functions:

比较函数应该接受两个参数,如果希望第一个参数排在第二个参数之前,返回一个负数。如果希望第一个参数排在第二个参数之后,返回一个正数,如果认为两个参数相等,返回0.

For example, if we want to sort by numeric ascending order, we can construct the following comparison function:

  function numcomp(num1, num2) {    //当num1较小时,我们希望num1排在前面    ifreturn -1;    //当num1较大时,我们希望num1排在后面    ifreturn1;    ifreturn0;  }

Or simply write it as:

  function numcomp(num1, num2) {    return num1 - num2;  }

Use the comparison function above as a parameter to achieve the ascending order of the values:

  var nums = [1, 2, 12, 4, 21];  nums.sort(numcomp);  alert(nums);

JavaScript Common Objects Array (1)

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.