JavaScript language essence Note 04 Array

Source: Internet
Author: User

Array
1 Number of array literals
2 length
3 Delete
4 Listing
5 Confusing places
6 methods
7 Dimensions

Array
1 Number of array literals

var empty = []; var numbers = [    ' zero ', ' one ', ' one ', ' one ', ' three ', ' four ',    ' Five ', ' six ', ' seven ', ' eight ', ' nine '];empty[1]/          /  undefinednumbers[1]        //  ' one ' empty.length       // 0numbers.length    //  

The array literal can appear where any expression can appear. The first value of the array gets the property name ' 0 ', the second value gets the property name ' 1 ', and so on.

The object literal produces a similar result:

var numbers_object = {    ' 0 ': ' zero ',  ' 1 ': ' One ',   ' 2    ': ' One ', ' 3 ': ' Three ', ' 4 ': ' Four ',  ' 5 ': ' Five ',    ' 6 ': ' Six ', '   7 ': ' Seven ', ' 8 ': ' Eight ',    ' 9 ': ' Nine ' };

But they also have some notable differences:

Numbers inherits from Array.prototype, and Numbers_object inherits from Object.prototype, so numbers inherits a lot of useful methods.

and Numbers_object didn't.

In most languages, all elements of an array require the same type. JS allows the array to contain values of any mixed type:

var misc = [    truefalsenull, undefined,    [True]  }, NaN,    infinity];misc.length    //  ten


2 length

Each array has a length property, but the JS array has no upper bounds. If you save an element with a number greater than or equal to the current length as a subscript, length increases to accommodate the new element. Array boundary errors do not occur. The value of the length property is the maximum integer attribute of this array plus 1. It is not necessarily equal to the number of attributes in the array.

var myArray = [];myarray.length             //  0myarray[true; Myarray.length             //  1000001//  MyArray contains only one property

The [] suffix subscript operator converts its expression to a string, and if the expression has the ToString method, the value of the method is used, and the string is used as the property name. If the string looks like an integer greater than or equal to the current length of the array and less than 4 294 967 295, then the length of the array will be reset to the new subscript plus 1.

The value of length can be set directly. Setting a larger length does not require allocating more space to the array. Setting the length will cause all attributes with a subscript greater than or equal to the new length to be deleted.

var numbers = [    ' zero ', ' one ', ' one ', ' one ', ' three ', ' four ',    ' Five ', ' six ', ' seven ', ' eight ', ' nine '= 3; // numbers to [' zero ', ' one ', ' both ']

By specifying the subscript as the current length of an array, you can append a new element to the end of the array.

Numbers[numbers.length] = ' shi '; // numbers changed to [' Zero ', ' one ', ' one ', ' one ', ' Shi ']

Sometimes the same thing can be done more easily with the push method:

Numbers.push (' Go '); // numbers changed to [' Zero ', ' one ', ' one ', ' one ', ' Shi ', ' go ']


3 Delete

Because the array of JS is actually an object, the delete operator can be used to remove elements from the array:

Delete numbers[2]; // numbers changed to [' Zero ', ' one ', Undefined, ' shi ', ' go ']

This will leave an empty hole in the array. This is because the elements that follow the deleted element retain their original name (subscript). What we usually want is to decrement the name (subscript) of each element behind it.

The JS array has a splice method that can delete elements and replace them with other elements. The first parameter is the ordinal in the array, and the second parameter is the number of elements to delete. Any additional parameters are inserted into the array at the point where the ordinal number is.

Numbers.splice (2, 1); // numbers changed to [' Zero ', ' one ', ' Shi ', ' go ']

The key value of the attribute with a value of ' Shi ' changes from ' 3 ' to ' 2 '. Each property that follows the deleted attribute must be removed and reinserted with a new key value, which may be inefficient for large arrays.


4 Listing

For statement traversal

var i;  for (i=0;i<numbers.length;i++) {    console.log (numbers[i]);}


5 Confusing places

JS, a common mistake is to use an object when the array must be used, or to use an array when the object must be used. The rule is simple: You should use an array when the property name is a small, sequential integer. Otherwise, the object is used.

The difference between the array and the object in JS itself is confusing. The typeof operator reports that the type of the array is ' object ', which does not make sense. You can only customize the Is_array function to determine:

var function (value) {    returntypeof value = = = ' object ' && value.constructor = = =  Array;};

However, it does not recognize arrays constructed from different windows (widow) or frames (frame). If you want to check which external arrays require more work:

var function (value) {    return value &&    typeof value = = = ' object ' &&     typeof Value.length = = = ' Number ' &&    typeof Value.splice = = = ' function ' &&// Is there a splice method    ! ( Value.propertyisenumerable (' length ')); whether the//length can be traversed through  for-in};


6 methods

JS provides a set of methods that act on arrays, which are functions stored in array.prototype. The Array.prototype can be expanded.

For example: Define a reduce method that takes a function and an initial value as a parameter.

array.prototype.reduce=function  (f, value) {    var  i;      for this. length; i + = 1)        {= f(this[i], value);    }     return value;};

Call Method:

//Create an arrayvardata = [4, 8, 15, 16, 23, 42];//define a function that asks for two numbersvarAdd =function(A, b) {returnA +b;}; // define a function that asks for a two number product 
varMult =function(A, b) {returnAb;};varsum = data.reduce (add, 0);//sum is 108varProduct = Data.reduce (mult, 1); //product is 7418880

Because arrays are objects, we can add methods directly to a single array:

// add a total method to an array function (  ) {    returnthis. Reduce (add, 0);}; var total = Data.total (  );    // Total is 108 .


7 Dimensions

JS does not have many arrays, but it supports an array of elements:

var matrix = [    [0, 1, 2],    [3, 4, 5],    [6, 7, 8]];matrix[2][1]< c8/>//  7

Create a matrix with initialization:

Array.matrix =function(M, n, initial) {varA, I, j, mat = [];  for(i = 0; i < m; i + = 1) {a= [];  for(j = 0; J < n; j + = 1) {A[j]=initial; } Mat[i]=A; }    returnMat;};//Create a 4 * 4 matrix filled with 0varMymatrix = Array.matrix (4, 4, 0);d Ocument.writeln (mymatrix[3][3]);//0//the method used to construct an identity matrixarray.identity=function(n) {varI, Mat = Array.matrix (n, N, 0);  for(i = 0; i < n; i + = 1) {Mat[i][i]= 1; }    returnMat;}; Mymatrix= Array.identity (4);d Ocument.writeln (mymatrix[3][3]);//1

Reference: "The JavaScript language essence" Douglas Crockford Zhao Zehin Shan Translation

Reprint please specify the source:

Jesselzj
Source: http://jesselzj.cnblogs.com

JavaScript language essence Note 04 Array

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.