JS organization memo (04)-array Basics

Source: Internet
Author: User

Concept: array (ArrayIs an ordered set of values. Each value is called an element (Element), Each element has a digital position in the array, called subscript (Index).

Type: array is a composite data type. An array is essentially a special object. It is an object with an additional function layer. For example, the following two rowsCodeAll return types are objects.

Typeof ([1, 2]);

VaR A = []; typeof ();

Features: the number of elements can be infinite, and the elements can be any type of data (the element types in the same array can be different ), the element subscript to be assigned can be discontinuous (the default value of undefined is undefined ).

 

1. Create an array

(1) Use the array directly

VaR A = []; // defines an array without elements, that is, an empty array. The array length is 0. In this case, a [0] = undefined = NULL

VaR B = [20, ["ASD", 5], "qwe"]; // The default undefined element is undefined. In this case, B [1] = undefined

 

(2) Use array () to construct a function

    • No Parameter

VaR A = new array (); // create an empty array without elements

    • If N parameters are specified, the first N values of the array are specified. Note that there are no two consecutive commas (,). This is different from the method of direct data transfer in the array.

VaR B = new array (20, ["ASD", 5], "qwe"); // This method seems inconvenient compared to the direct amount of arrays.

    • Pass a numeric Parameter

VaR A = new array (10); // creates an array with 10 elements, that is, a. Length = 10. The value of each element is undefined.

 

2. Operations on array elements

Only some notes are recorded. You can find relevant information when necessary.

Unordered attribute in the array, not involved in the operation of array elements.

(1) Add new elements

    • Add an element by subscript

Through the array subscript, you can add any type of elements to any position of the array at any time. You only need a simple assignment operation. For example:

VaR arr = []; arr [10] = "nihao"; // assign a value to the 10 elements (11th elements in an ordered sequence) in the array, you do not need to care whether the elements at other locations are defined.

It can be seen that the array in JS can be sparse (sparse), and the subscript of valid values in the array must not be continuous. The default value of the element that is not defined is undefined, and JS does not allocate memory to it.

    • Add element by attribute name

This is a special and interesting aspect in arrays, mainly because arrays are essentially objects, so they should naturally have all the features of objects. For example:

VaR A = []; A ["name"] = "an array for test. "; // adds an attribute named" name "to array object A. The attribute value is a string and fully complies with the syntax.

Differences and relationships between arrays and objects (not necessarily accurate, according to your own understanding)

<1> arrays belong to one type of objects, but are higher than objects. As mentioned above, the attribute name in the object is an identifier or string, and the subscript of the array should be considered as the attribute name of the array theoretically, however, this attribute name is represented by an integer (that is, the lower value. In this case, the array belongs to the object and it seems to be better understood.

<2> in terms of definition, the attributes of an object are unordered, while arrays are a set of ordered values. However, arrays are also an object, so they can naturally contain unordered attributes. Is this a conflict with the definition? But who is calling JS is a loose language, so it cannot be used. Sometimes I feel that JS language is very clever, and I am very close to my life. [There is no certainty in everything, and only contradictions exist absolutely .]

However, you don't have to worry about it. The existence of such unordered elements will not affect some normal operations of arrays. For example, in the previous example, although a "name" attribute is added to the empty array A, the value of A. length is still 0.

Note: The object does not have the Length attribute. Of course, the Length attribute is not unique to the array. The function described later also has the Length attribute, but the meaning is different.

<3> it seems that an array with unordered attributes is added to an object that contains the originally defined array object in the traditional sense, and additional unordered attributes. Operations on this object are still directly performed on the previously defined array when the tag is used.

 

(2) Delete array elements

    • The delete operator only sets an array element to an undefined value, but the element still exists, that is, the subscript position of all elements remains unchanged.
    • To delete an element, you must use the specified array method:

Array. Shift () method -- no parameter. For the array itself, the first element is always deleted, and the returned value is the deleted element. After deletion, the array subscript is automatically migrated.

Array. Pop () method -- no parameter. The last element is always deleted. The returned value is the deleted element. After deletion, the array subscript is automatically migrated.

Array. splice () method -- when two Integer Parameters are passed, the elements in the continuous subscript range are deleted from an array.

The following array methods are also described in detail.

 

(3) truncation or growth of Arrays

The Length attribute of the array can be read or written.

If the value of the new length is smaller than the length value of the current array, the array is truncated. All elements other than the length are discarded and the value is lost.

If the value of the new length is greater than the length value of the current array, the array is "increased", and the value on the new position is undefined by default.

Here are some examples to illustrate some operations on array elements:

 <  Script  Type  = "Text/JavaScript"  Language  = "JavaScript"> VaR B = [{X: 1}, 20, "ABC" ,,[ "ASD" , 5], True ]; // B. The length value is 6  Delete B [1]; // Set the value of Element B [1] to undefined. B should be changed to [{X: 1}, "ABC", ["ASD", 5], true] B [2] = undefined; // Same as the previous sentence. B should be changed to [{X: 1}, ["ASD", 5], true] B. ID = "ID" ; // Add an unordered attribute named "ID" to the array object. Document. Write (B. tostring () + "<Br/>" ); // <1> is the output ID? B [ "ID" ] = "New Value" ;// <2> Can I perform operations on the unordered attribute added? B. Pop (); // <3> Delete the last element of the array. Will the length of the array change? Delete "true" in the ordered array or the newly added element ID?  For (P In B) {document. Write (p + ":" + B [p] + ";" ); // <4> traverse array elements. Will IDS be output? } Document. Write ( "<Br/>" + B. Length ); // <5> result 5 or 6?  </  Script  > 

After running, the page output result is as follows:

[Object object], ASD, 5, true

0: [object]; 2: undefined; 4: ASD, 5; ID: new ID;

5

Answer questions before running:

Integrated question <1>, <3>, and <5>: the ID and its value are not output in the first row. The pop () operation does not delete the ID, but deletes the last element "true" in the ordered array ". The value of length is reduced by 1, which should be caused by pop.

-- Result conjecture: when using the array internal method for B, only the original array object is actually operated (except for the unordered naming attribute added ). And the length value is not affected by the unordered attribute. It depends only on the original array.

Problem <2>: the second row of the result. The value of ID is "new ID", indicating that the array can operate on the unordered attribute added.

Problem <4>: The for/in method of traversing the array can output all attribute values of the current array object, including unordered attributes.

 

3. array Methods

(1) join () method

-- If the original array remains unchanged, "a string composed of all elements of the array, separated by commas by default" is returned. The return value type is string ).

If a parameter is specified, the array elements in the result string are separated by the specified parameter (string type). If no parameter is specified, the parameters are separated by commas. Example:

<ScriptLanguage= "JavaScript"Type= "Text/JavaScript"> VaRA = [1, 2,"ASD", 4]; document. Write (A. Join ());// 1, 2, ASD, 4Document. Write (A. Join ("0"));// 1020304Document. Write (A. Join ("*"));// 1*2 * ASD * 4Document. Write (A. tostring ());// 1, 2, ASD, and 4 Original arrays unchanged</Script>
 
This method is exactly the opposite of string. Split (). The latter Splits a string into several fragments to create an array.
 
 

(2) reverse () method

-- Directly operate on the original array and return the array after the array elements are arranged in reverse order. The result is as follows:

 
VaRA = [1, 2,"ASD", 4]; document. Write (A. Reverse ());// 4, ASD, 2, 1Document. Write (A. tostring ());// 4, ASD, 2, 1

 

(3) sort () method

-- Directly operate on the original array and return the sorted array. Note the following:

    • If no parameter is specified, it sorts array elements alphabetically (even if all array elements are numbers)
 
VaRA = [33, 4,111, 22,234, 12]; document. Write (A. Sort ());// Result: 22,234
    • If the array contains undefined elements, these elements are placed at the end of the array.
    • To sort arrays in other order, you must use a comparison function as a parameter of the sort () method,

For example, the array is sorted by the value size as follows:

Document. Write (A. Sort (Function(A, B ){ReturnA-B;// Sort by numbers in ascending order: 111,234}); Document. Write (A. Sort (Function(A, B ){ReturnB-;// Sort by number in descending order: 234,111, 22}));

The preceding example uses the number of functions directly as the parameter of the sort () method. You can also pass the function name. Sort the case-insensitive letters in ascending order as follows:

 
FunctionF (S1, S2 ){If(S1.tolowercase () <s2.tolowercase ()){Return-1 ;}Else if(S1.tolowercase ()> s2.tolowercase ()){Return1 ;}Else return0 ;}// Define a comparison function f first
VaRSTR = ["AGP","Aaddf","Better"]; Document. Write (Str. Sort (f ));// The result shows aaddf, AGP, and better.

 

(4) slice () method

-- If the original array remains unchanged, a segment (slice) of the specified array is returned, or a subarray is returned. Notes:

If only one parameter is passed, the returned array is a subscript starting from the parameter value to all elements at the end of the original array.

If two parameters are passed, the parameters indicate the starting and ending subscript positions of the returned fragments respectively.

A negative integer can be passed. The value-1 is the first element to return to the exponent group. (This is easy to understand, and the example is omitted)

 

(5) splice () method

-- This isInsert or deleteThe common method of array elements.

-- Directly operate on the original array. The original array is converted to the processed array and the returned value isDeletedArray composed of elements.

This method can be used to set multiple parameters: the first parameter specifies the location, and the second parameter specifies the number of deleted elements. You can also add any number of parameters to indicate the array elements to be inserted at this position.

Some examples:

VaRP, q; P = [1, 2, 3, 4, 5]; q = P. splice (3 );// P = [1, 2]; q = [4, 5]Q = P. splice (1, 2 );// P = [1]; q = [2, 3]

 
VaRM, N; M = [1, 2, 3, 4, 5]; n = M. splice (2, 0,'A','B');// M = [1, 2, 'A', 'B', 3, 4, 5]; N: []N = M. splice (2, 2, [1, 2], 3 );// M = [1, 2], 3, 3, 4, 5]; N: ['A', 'B']
 
 

(6) Push (), pop (), shift (), unshift ()

Push () -- attaches one or more new elements to the end of the specified array.

Pop () -- directly operate on the array, delete the last array element, and return the deleted Value. Note that pop has no parameter and only one value is deleted at a time.

Shift () -- directly operate on the array, delete and return the first array element.

Unshift () -- attaches one or more new elements to the beginning of the specified array.

 

(7) Some New Methods

Javascript 1.5 is supported since Firefox 1.6. In JavaScript 1.6, JavaScript arrays have added several useful methods: indexof, lastindexof, every, filter, foreach, map, and some, the first two can be used for fast element locating, while the last few can be classified as iterative methods.

However, these new methods are not supported by all browsers. If you are interested, you can refer to: Introduction to new methods in Javascript 1.6 arrays to introduce the use of these methods one by one, and solutions for unsupported browsers.

 

4. objects similar to Arrays

In this article, we also mentioned the difference and connection between arrays and objects: the array has the Length attribute while the object does not.

Conjecture: Isn't that if we define an object at the beginning and add the Length attribute to it, it can be processed as an array? (Of course, it should not be completely converted into an array, but it can be treated as an object similar to an array ")

Although such an array-like object has the Length attribute, it cannot call the array method because it is not an array in essence.

However, you can use the code to traverse the array to traverse such objects. For example:

    script   language   =" JavaScript "  type   =" text/JavaScript "> var  A ={};  // define the object   for  ( var  I = 0; I <10; I ++) {A [I] = I * I; 
}A. Length = I;// This is critical because the object itself does not have the Length attribute.For(VaRJ = 0; j <A. length; j ++) {document. Write (A [J] +";");// Result output: 0; 1; 4; 9; 16; 25; 36; 49; 64; 81;}</Script>

Analysis: when adding attributes to object A, I in object a [I] should be converted to string processing theoretically, proving this conjecture:

But can I use a numeric string as a subscript to access an array ???

-- The answer is: yes.

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.