An analysis of the array type system _javascript techniques in JavaScript

Source: Internet
Author: User
Tags array length chr javascript array

Front.

An array is a sequence of values, in contrast, the object's property name is unordered. In essence, arrays use numbers as lookup keys, while objects have user-defined property names. JavaScript does not have a true associative array, but the object can be used to implement the associated functionality

Array () is just a special type of object (), that is, the array () instance is essentially an object () instance that has some extra functionality. Arrays can hold values of any type that can be updated or deleted at any time, and the size of the array is dynamically adjusted

In addition to objects, the array type may be the most commonly used type in JavaScript. Also, 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 literal syntax and using the array () constructor

"Literal volume"

Using array literals is the simplest way to create an array, separating the elements of the array with commas in square brackets

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

Although the JavaScript array and the array in other languages are ordered lists of data, unlike other languages, each item of a JavaScript array can hold any type of data

var misc = [1.1,true, "a"]; 3 different types of elements

The values in an 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 literals or other array literals

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

If the element of an array is an array, a multidimensional array is formed

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

[note] The array constructor is not invoked when the number literal notation is used

"Constructor"

Three ways to call a constructor

"1" has no arguments, creating an empty array

This method creates an empty array without any elements, equal to the direct amount of the array []

"2" has a numeric parameter that specifies the length of the array

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

[note] If there is one other type of argument, an array of only one is created that contains that value

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

When "3" has more than one argument, the parameter represents the concrete element 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 the array () constructor, you can omit the new operator

var a1 = Array ();
var a2 = Array (a);
var a3 = Array (1,2,3);

Array essence

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

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

The special body of an array now, its key name is an ordered set of integers (0,1,2 ...). Because the key names of the array members are fixed, the array does not specify a key name for each element, and each member of the object must specify the key name

var arr = [' A ', ' B ', ' C '];
Console.log (Object.keys (arr));//["0", "1", "2"]
var obj = {
name1: ' A ',
name2: ' B ',
name3: ' C '
};

An array is a special form of an object, using square brackets to access an array element just as you would access an object's properties with square brackets

The JavaScript language stipulates that the object's key name is a string, so the array's key name is actually a string. This can be read numerically because the key name of the non string is converted to a string and then used as the property name

o={}; Create a normal object o[1]= "one";/////////////
numeric key name is automatically converted to string
var arr = [' A ', ' B ', ' C '];
arr[' 0 ']//' A '
arr[0]//' a '

However, be sure to differentiate between the array index and the object's property name: All indexes are property names, but only the integer property name between 0~232-2 (4294967294) is indexed

var a = [];
Index
a[' 1000 ' = ' abc ';
A[1000]//' ABC '
//index
a[1.00] = 6;
A[1]//6

  [note] A single value cannot be an identifier (identifier). Therefore, array members can only be represented by the square brackets method

var arr = [1, 2, 3];
ARR[0];//1
Arr.0;//syntaxerror

You can use negative or non-integer indices to index an array. But since it is not within the range of the 32-0~2-2, it is only the property name of the array, not the index of the array, and the obvious feature is not to alter the length of the array

var a = [1,2,3];
Property name
a[-1.23]=true;
Console.log (a.length);//3
//Index
a[10] = 5;
Console.log (a.length);//11
//property name
a[' abc ']= ' testing ';
Console.log (a.length);//11

Sparse arrays

A sparse array is an array that contains discontinuous indexes starting at 0

The most straightforward way to create a sparse array of "1" is to use the delete operator

var a = [1,2,3,4,5];
Delete a[1];
Console.log (a[1]);//undefined
Console.log (1 in a);//false

An element value can be omitted between commas in the "2" array, and a sparse array can be created by omitting the element value

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

[note] There is a difference between the omitted element value and the element value of the undefined value

var a =[1,,3,4,5];
Console.log (a[1]);//undefined
Console.log (1 in a);//false
var a =[1,undefined,3,4,5];
Console.log (a[1]);//undefined
Console.log (1 in a);//true

If you use commas at the end of an array, there is a difference between browsers. The standard browser ignores the comma, and the ie8-browser adds the undefined value at the end

Standard browser output [1,2], while ie8-browser output [1,2,undefined]
var a = [1,2,];
Console.log (a);
Standard browser Output 2, while ie8-browser output 3
var a = [,,];
Console.log (a.length);

Sparse enough arrays are usually slower to implement than dense arrays, and memory utilization is higher, and the time to find elements in such an array is as long as the normal object properties are found

Array length

Each array has a length attribute, which distinguishes it from the regular JavaScript object. For dense (or not sparse) arrays, the Length property value represents the number of elements in the array, and the value is 1 greater than the largest index in the array

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

When an array is a sparse array, the Length property value is greater than the number of elements and, similarly, its value is 1 greater than the largest index in the array

[,,,].length; 3
(Array). LENGTH;//10
var a = [1,2,3];
Console.log (a.length);//3
Delete a[1];
Console.log (a.length);//3

The specificity of the array is mainly reflected in the length of the array can be dynamically adjusted:

"1" If you assign a value to an array element and the index i is greater than or equal to the length of an existing array, the value of the length property is set to I+1

var arr = [' A ', ' B '];
Arr.length//2
arr[2] = ' C ';
Arr.length//3
arr[9] = ' d ';
Arr.length//
arr[1000] = ' e ';
Arr.length//1001

When "2" sets the length property to be a non-negative integer n less than the current length, the element with the current array index value greater than or equal to n is removed from the

a=[1,2,3,4,5]; Starting with an array of 5 elements
a.length = 3;//Now A is [1,2,3]
a.length = 0;//delete all elements. A is []

Array (5)

[note] An effective way to empty an array is to set the length property to 0

var arr = [' A ', ' B ', ' C '];
arr.length = 0;
ARR//[]

"3" Sets the length property value of the array to be greater than its current size. This doesn't actually add a new element 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]);//undefined
Console.log (1 in a);//false

If you set length to an illegal value (that is, a value other than the 0--232-2 range), JavaScript will complain

Set negative
[].length = -1//rangeerror:invalid Array length
//array element is greater than or equal to 2 of 32 times
[].length = Math.pow (2,32)/Ra Ngeerror:invalid array length
//Set string
[].length = ' abc '//rangeerror:invalid array length

Because arrays are objects in nature, you can add attributes to an array, but this does not affect the value of the length property

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

Array traversal

The most common way to traverse an array element with 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]);
}

But if the array is a sparse array, use a For loop, and you need to add some conditions

Skipped 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 for/in loops to process sparse arrays. The loop assigns an enumerable property name, including an array index, to the loop variable at a time. An index that does not exist will not traverse the

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

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

var a = [1,,, 2];
A.B = ' B ';
for (var i in a) {
console.log (a[i]);//1 2 ' B '
} 
//Skip I
var a = [1,,, 2] that is not a non-negative integer;
A.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 the properties of an object in a different order. Usually the traversal implementation of an array element is ascending, but it is not guaranteed to be the case. In particular, if an array has both object attributes and arrays, the returned property names are likely to be in the order of creation rather than the size order of the numeric values. If the algorithm relies on the order of traversal, it is best not to use for/in instead of the regular for loop

Class Array

Objects that have the length property and the corresponding non-negative integer attribute are called class arrays (Array-like object)

Class Array Demo
var a = {};
var i = 0;
while (I <) {
a[i] = i*i;
i++;
}
A.length = i;
var total = 0;
for (var j = 0; J < A.length; J + +) {Total
+ = A[j];
}

 There are three common class array objects:

  "1" Arguments object

Arguments object
function args () {return arguments}
var arraylike = args (' A ', ' B ');
ARRAYLIKE[0]//' A '
arraylike.length//2
arraylike instanceof Array//False

  Objects returned by the "2" 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 immutable values, so when treated as arrays, they are read-only. Array methods such as push (), sort (), reverse (), splice () modify the array, they are invalid on the string, and the error

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 slice method of the array turns the class array object into a true array

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

JavaScript array methods are deliberately defined as generic, so they are not only applied to real arrays but also work correctly on class array objects. In ECMAScript5, all array methods are generic. In ECMAScript3, all methods except ToString () and tolocalestring () are also generic

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 '

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.