JavaScript array attributes

Source: Internet
Author: User
Tags javascript array

Original: JavaScript array attributes

An array is a linearly allocated memory that computes offsets and accesses the elements in an integer. An array is a data structure with excellent performance. 1. Array literals

Array literals provide a very convenient notation for creating new arrays. An expression of multiple values separated by commas. The array literal allows to appear where any expression can occur. The first value of the array gets the property name ' 0 ', the second value gets the property name ' 1 ', and so on:

1             var empty = []; 2             var numbers = [3                 ' zero ', ' one ', ' one ', ' three ', ' four ',4                             ]; 6
       7             Console.log (empty[1]);//undefined 8             console.log (numbers[1]);//' One '             9             console.log ( EMPTY.LENGTH);//011             console.log (numbers.length);//   

Object literal:

1             var numbers_object = {2                 ' 0 ': ' Zero ', 3                 ' 1 ': ' One ', 4                 ' 2 ': ' Both ', 5                 ' 3 ': ' Three ' 
       
         6                 ' 4 ': ' Four '
        , 7 ' 5 ': ' Five ',8 ' 6 ': ' Six ', 9 ' 7 ': ' Serven ', ' 8 ': 'eight ', one ' 9 ':' Nine ' n};      
          

The results are similar, numbers and Numbers_object are objects with 10 attributes, and those attributes have exactly the same name and value. But they also have some notable differences, numbers inherit from Array.prototype, and numbers_object inherit from Object.prototype, so numbers inherited a lot of useful methods. At the same time, numbers also has a strange length property, while Numbers_object does not.

In most languages, all elements of an array require the same type. JavaScript allows you to include values of any mixed type in the array:

1                 var misc = [2                     ' string ', 98.6, True, false, null, undefined,3                     [' nested ', ' array '], {object:true                                     ];6                 7                 console.log (misc.length);//   

In JavaScript, the brackets [] represent an array, or they can be understood as arrays of objects; The curly braces {} represent an object, [] and {} are used together to form an array of objects, as shown in the example above.

2. Length

Each number has a length property, and unlike most other languages, the length of the JavaScript array is not upper bound. If you store an element with a number greater than or equal to the current length as a subscript, the length value is incremented to accommodate the new element, and the array out of bounds error does not occur.

The value of the length property is the maximum integer property name of this array plus 1, which is not necessarily equal to the number of attributes in the array:

1                 var myArray = [];2                 Console.log (myarray.length);//                 4                 myarray[1000000] = True; 5                 Console.log (myarray.length);//100000016                 //MyArray contains only one property 

The [] post-subscript operator converts the expression it contains into a string, and if the expression has the ToString method, the value of the method is used. This string is used as the property name. If the string looks like a positive integer that is greater than or equal to the current length of this array and less than 4294967295, then the length of the array is reset to the new subscript plus 1, otherwise the long value of the array is longer.

3. Delete

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

1                 var numbers = [' zero ', ' noe ', Undefined, ' shi ', ' Go '];2                 delete numbers[2];3 console.log                 ( NUMBERS.LENGTH);//5 

Unfortunately, that would leave a space in the array. This is because the elements that follow the deleted elements retain their original properties. What you usually want is to decrement the properties of each element behind.

Fortunately, the JavaScript array has a splice method. It can operate on an array, remove elements and replace them with other elements. The 1th parameter is an ordinal in the array, and the 2nd parameter is the number of elements to delete. Any additional parameters are inserted into the array at the point where the sequence number is located:

1                 var numbers = [' zero ', ' noe ', Undefined, ' shi ', ' Go '];2                 numbers.splice (2, 1);    3                 Console.log (numbers.length);//4 

The key value of the attribute with a value of ' Shi ' changes from ' 3 ' to ' 2 '. Because each property after the deleted property must be removed and reinserted with a new key value, this can be inefficient for large arrays.

4. Easily confusing places

In JavaScript programming, 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 an array and an object is confusing for JavaScript itself. The typeof operator reports that the type of the array is ' object ', which makes no sense, JavaScript does not have a good mechanism to distinguish between arrays and objects, and we can compensate for this defect by defining our own Is_array function:

1                 var array = [2                                     ]; 4                  5                 var obj = {6                     ' 0 ': ' Zero ', 7                                     }; 9                 1 0                 var is_array = function (value) {One return Object.prototype.toString.apply (value) = = = ' [Object array] ' } ; Console.log (Is_array (array));//True15 Console.log (Is_array (obj));//False      

5. Methods

JavaScript provides a set of methods that are available for arrays. These methods are stored in Array.prototype functions, Object.prototype and Array.prototype can be expanded, for example, suppose we want to add a method to the array, which allows our team array to calculate:

1                 //By adding a method to Function.prototype to make the method available to all functions 2                 Function.prototype.method = function (name, func) {3                     This.prototype[name] = func; 4                     return this                }; 6                  7                 array.method (' Reduce ', function (f, Value) {8                     var i; 9 for (i = 0; i < this.length; i++) {Ten value = f (This }12 return value;13} );

By extending a function to Array.prototype, each array inherits this method. In this example, we define a reduce method, which takes a function and an initial value as a parameter. It facilitates this array, invokes the function with the current element and the initial value, and calculates a new value. When finished, it returns the new value.

If we pass in a function that adds two numbers, it calculates the sum of the sums. If we pass in a function that multiplies two arrays, it calculates the product of both:

1                 //Create an array of Arrays 2                 var data = [4, 8,,, Max]; 3                   4                 //define two simple functions, one is to add two numbers and the other is to multiply two numbers. 5                 VA  R add = function (A, b) {6                     return a +                }; 8                  9                 var mult = function (A, b) {Ten                     return a * };12 13//Call the data's reduce method and pass in the Add function. var sum = data.reduce (add, 0), console.log (sum);//10816 17//Call R again Educe method, this time the mult function is passed var product = Data.reduce (mult, 1); Console.log (product);//741888020 21//Because the array is actually an object, we can To add a method directly to a single array: data.total = function () {this.reduce (add, 0 };25 Console.log (Data.total ());//1         ,

6. Specify the initial value

Arrays of JavaScript typically do not preset values. If you use [] to get a new array, it will be empty. If you access a non-existent element, the resulting value is undefined. If you know the problem, or if you set his value very predictably before trying to get each element, then it's all right. However, if you implement an algorithm that assumes that each element starts with a known value (for example, 0), then you must prepare the array yourself. JavaScript should provide something like Array.dim to do this, but we can easily correct this negligence:

1                 array.dim = function (dimension, initial) {2                     var a = [], I; 3 for                     (i = 0; i < dimension; i++  {4                         A[i] =                    } 6                     return }; 8 9//Create an array of 10 0 with a var MyArray = Array.dim (ten, 0);   

JavaScript does not have a multidimensional array, but, like most Class C languages, it supports arrays of elements array:

1                 var matrix = [2                     [0, 1, 2],3                     [3, 4, 5],4                     [6, 7, 8                ];6                 7                 Console.log ( MATRIX[2] [1]);//7   

JavaScript also provides better support for matrices:

1                 array.matrix = function (m, n, initial) {2                     var A, I, j, mat = []; 3 for                     (i = 0; i < m; i++< c17>) {4                         a = []; 5 for                         (j = 0; J < N; j + +) {6                             a[j] = } 8 mat[i] = }10 return  };12 13//Construct a 0-filled 4 * 4 matrix var mymatrix = Array.matrix (4, 4, 0 console.log (mymatrix); Console.log (Mymatrix[3] [3 ]);//0        

4 * 4 matrix filled with 0:

1                 //method used to construct a unit matrix 2                 array.identity = function (n) {3                     var i, mat = Array.matrix (n, N, 0); 4 for                     ( i = 0; I < n; i++) {5                         mat[i] [i] = 1                    } 7                     return }; 9 Mymatrix = array.identity (4 console.log (Mymatri x); Console.log (Mymatrix[3] [3]);//1     

Unit matrix:

JavaScript array attributes

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.