Analysis on the array type system in JavaScript, javascriptarray

Source: Internet
Author: User
Tags javascript array

Analysis on the array type system in JavaScript, javascriptarray

Previous

An array is a set of values in order. The attribute names of objects are unordered. In essence, arrays use numbers as search keys, and objects have custom attribute names. Javascript does not actually associate arrays, but objects can be used to implement Association functions.

Array () is only a special type of Object (). That is to say, an Array () instance is basically an Object () instance with some additional functions. An array can store any type of values. These values can be updated or deleted at any time, and the array size is dynamically adjusted.

In addition to objects, the Array type may be the most common type in javascript. In addition, arrays in javascript are quite different from arrays in most other languages. This article describes the Array type in javascript.

Create an array

There are two ways to create an Array: using the literal syntax and using the Array () constructor

[Literal]

Using array literal is the easiest way to create an array. Separate array elements with commas in square brackets.

Var empty = []; // array without elements var primes = [2, 3, 5, 7, 11]; // array with 5 values

Although javascript arrays and arrays in other languages are an ordered list of data, unlike other languages, each of the javascript Arrays can save any type of data.

Var misc = [1.1, true, "a"]; // three elements of different types

The values in the array literal are not necessarily constants. They can be arbitrary expressions.

var base = 1024;var table = [base,base+1,base+2,base+3];

It can contain object literal or other array literal

var b = [ [1,{x:1,y:2}],[2,{x:3,y:4}] ];

If the array element is an array, a multi-dimensional array is formed.

var a = [[1, 2], [3, 4]];

[Note] Array constructor is not called when numeric literal representation is used.

[Constructor]

You can call constructors in three ways.

[1] Create an empty array without Parameters

// This method creates an empty Array without any elements, which is equivalent to directly adding [] var a = new Array ();

[2] There is a numeric parameter used to specify the length of the array

var a = new Array(10);console.log(a);//[]console.log(a[0],a.length);//undefined 10

[Note] If a parameter of another type exists, an array containing only one item is created.

var a = new Array('10');console.log(a);//['10']console.log(a[0],a.length);//10 1

[3] When multiple parameters exist, the parameters are represented as specific elements of the array.

var a = new Array(1,2,3);console.log(a);//[1,2,3]console.log(a[0],a[1],a[2]);//1 2 3

When using Array () to construct a function, the new operator can be omitted.

var a1 = Array();var a2 = Array(10);var a3 = Array(1,2,3);console.log(a1,a2,a3);//[] [] [1,2,3] 

Array nature

An array is a set of values in order. In essence, an array is a special object.

typeof [1, 2, 3] // "object"

The special characteristics of an array are that its key names are a group of Integers (, 2…) arranged in order ...). Because the key names of array members are fixed, you do not need to specify a key name for each element in the array, and each member of the object must specify a key name.

var arr = ['a', 'b', 'c'];console.log(Object.keys(arr));// ["0", "1", "2"]var obj = {name1: 'a',name2: 'b',name3: 'c'};

Arrays are special forms of objects. Using square brackets to access array elements is the same as using square brackets to access object attributes.

The javascript language specifies that all key names of an object are strings. Therefore, the key names of arrays are actually strings. The reason why the value can be read is that the key name of a non-string is converted into a string and used as the attribute name.

O ={}; // create a common object o [1] = "one "; // index it with an integer // The value key name is automatically converted to the string var arr = ['A', 'B', 'C']; arr ['0'] // 'A' arr [0] // 'A'

However, the attribute names of the array index and object must be distinguished: All indexes are attribute names, but only 0 ~ The integer attribute name between 232-2 (4294967294) is the index

Var a = []; // index a ['123'] = 'abc'; a [1000] // 'abc' // index a [1000] = 6; a [1] // 6

[Note] a separate value cannot be used as an identifier ). Therefore, array members can only be represented by square brackets.

var arr = [1, 2, 3];arr[0];//1arr.0;//SyntaxError

You can use negative or non-integer values to index the array. But because it is not 0 ~ So it is only the attribute name of the array, rather than the index of the array. The obvious feature is that the length of the array is not changed.

Var a = [1.23, 3]; // attribute name a [-] = true; console. log (. length); // 3 // index a [10] = 5; console. log (. length); // 11 // attribute name a ['abc'] = 'testing'; console. log (. length); // 11

Sparse array

A sparse array is an array that contains discontinuous indexes starting from 0.

[1] The most direct way to create a sparse array is to use the delete operator.

var a = [1,2,3,4,5];delete a[1];console.log(a[1]);//undefinedconsole.log(1 in a);//false

[2] element values can be omitted between commas in an array, and sparse Arrays can be created by omitting element values.

var a =[1,,3,4,5];console.log(a[1]);//undefinedconsole.log(1 in a);//false

[Note] the omitted element values and values are different from those of undefined elements.

var a =[1,,3,4,5];console.log(a[1]);//undefinedconsole.log(1 in a);//falsevar a =[1,undefined,3,4,5];console.log(a[1]);//undefinedconsole.log(1 in a);//true

If a comma is used at the end of an array, there is a difference between browsers. The standard browser ignores the comma, while the IE8-browser adds the undefined value to the end.

// The standard browser outputs [1, 2], while the IE8 browser outputs [1, 2, undefined] var a = [1, 2,]; console. log (a); // standard browser outputs 2, while IE8-browser outputs 3var a = [,]; console. log (. length );

An array that is sparse enough is generally slower than a dense array and has a higher memory utilization. The time for searching elements in an array is as long as that of common object attributes.

Array Length

Each array has a length attribute, which distinguishes it from a common JavaScript Object. For dense (non-sparse) arrays, The length attribute value indicates the number of elements in the array, and its value is 1 larger than the maximum index in the array.

[]. Length // => 0: the array has no elements ['A', 'B', 'C']. length // => 3: The maximum index is 2, and the length is 3

When an array is a sparse array, the length attribute value is greater than the number of elements. Similarly, the value is 1 larger than the maximum index in the array.

[,,,].length; //3(Array(10)).length;//10var a = [1,2,3];console.log(a.length);//3delete a[1];console.log(a.length);//3

The special nature of arrays is that the length of arrays can be dynamically adjusted:

[1] If a value is assigned to an array element and index I is greater than or equal to the length of an existing array, the value of the length attribute is set to I + 1.

var arr = ['a', 'b'];arr.length // 2arr[2] = 'c';arr.length // 3arr[9] = 'd';arr.length // 10arr[1000] = 'e';arr.length // 1001

[2] When the length attribute is set to a non-negative integer n less than the current length, elements whose index value is greater than or equal to n will be deleted from the array.

A = [, 5]; // starts from the array of 5 elements. length = 3; // now a is [1, 2, 3]. length = 0; // delete all elements. A is [] a. length = 5; // The length is 5, but there is no element, just like new

Array (5)

[Note] An Effective Way to clear an array is to set the length attribute to 0.

var arr = [ 'a', 'b', 'c' ];arr.length = 0;arr // []

[3] set the length attribute value of the array to be greater than its current length. In fact, this will not add new elements to the array. it just creates an empty area at the end of the array.

var a = ['a'];a.length = 3;console.log(a[1]);//undefinedconsole.log(1 in a);//false

If the length is set to an invalid value (that is, a value out of the 0-2 32-2 range), javascript will report an error.

// Set the negative value []. length =-1 // RangeError: Invalid array length // The number of array elements is greater than or equal to the power 32 of 2 []. length = Math. pow () // RangeError: Invalid array length // set the string []. length = 'abc' // RangeError: Invalid array length

Because the array is essentially an object, you can add attributes to the array, but this does not affect the value of the length attribute.

var a = [];a['p'] = 'abc';console.log(a.length);// 0a[2.1] = 'abc';console.log(a.length);// 0

Array Traversal

The most common way to traverse array elements using a for Loop

var a = [1, 2, 3];for(var i = 0; i < a.length; i++) {console.log(a[i]);}

Of course, you can also use the while LOOP

var a = [1, 2, 3];var i = 0;while (i < a.length) {console.log(a[i]);i++;}var l = a.length;while (l--) {console.log(a[l]);}

However, if the array is a sparse array and the for loop is used, some conditions need to be added.

// Skip The Nonexistent element var a = [1, 2]; for (var I = 0; I <a. length; I ++) {if (! (I in a) continue; console. log (a [I]);}

You can also use the for/in loop to process sparse arrays. Each time a loop assigns an enumerable attribute name (including an array index) to the loop variable. Indexes that do not exist will not be traversed

var a = [1,,,2];for(var i in a){console.log(a[i]);} 

Because the for/in loop can enumerate the inherited attribute names, such as the method added to Array. prototype. For this reason, the for/in loop should not be used on the array, unless additional detection methods are used to filter unwanted attributes

Var a = [1, 2];. B = 'B'; for (var I in a) {console. log (a [I]); // 1 2 'B'} // skip the ivar a = [1, 2];. B = 'B'; for (var I in a) {if (String (Math. floor (Math. abs (Number (I ))))! = I) continue; console. log (a [I]); // 1 2}

The javascript specification allows the for/in loop to traverse object attributes in different order. In general, the traversal of array elements is implemented in ascending order, but it cannot be guaranteed that this is the case. In particular, if an array has both object attributes and array elements, the returned attribute names may be in the order of creation rather than the order of numerical values. If the algorithm depends on the order of traversal, it is best not to use for/in instead of the regular for loop.

Class Array

An object with the length attribute and corresponding non-negative integer attribute is called an array (array-like object)

// Class array demonstration var a ={}; var I = 0; while (I <10) {a [I] = I * I; I ++;}. length = I; var total = 0; for (var j = 0; j <. length; j ++) {total + = a [j];}

 There are three common class array objects:

  [1] arguments object

// Function args () {return arguments} var arrayLike = args ('A', 'B'); arrayLike [0] // 'A' arrayLike. length // 2 arrayLike instanceof Array // false

  [2] The object returned by the DOM method (such as the document. getElementsByTagName () method)

// DOM element var elts = document. getElementsByTagName ('h3 '); elts. length // 3 elts instanceof Array // false

  [3] string

// String 'abc' [1] // 'B' abc '. length // 3 'abc' instanceof Array // false

[Note] strings are unchangeable values, so they are read-only when they are viewed as arrays. Array methods, such as push (), sort (), reverse (), and splice (), modify the array. They are invalid in the string and report errors.

var str = 'abc';Array.prototype.forEach.call(str, function(chr) {console.log(chr);//a b c});Array.prototype.splice.call(str,1);console.log(str);//TypeError: Cannot delete property '2' of [object String]

The array slice method converts the class array object into a real Array

var arr = Array.prototype.slice.call(arrayLike);

The javascript array method is specifically defined as generic, so they can work correctly not only in real arrays but also in array objects of classes. In ECMAScript5, all array methods are generic. In ECMAScript3, all methods except toString () and toLocaleString () are also common.

var a = {'0':'a','1':'b','2':'c',length:3};Array.prototype.join.call(a,'+');//'a+b+c'Array.prototype.slice.call(a,0);//['a','b','c']Array.prototype.map.call(a,function(x){return x.toUpperCase();});//['A','B','C']

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.