How to create an array in Javascript

Source: Internet
Author: User
Tags php foreach javascript array

 

(From: http://www.xiaoxiaozi.com/2009/06/29/1020)

Arrays are one of the most involved data types since I learned programming. To put it bluntly, arrays are nothing more than key-value pairs. I still remember that when I first joined my job, a PHP foreach loop almost made me vomit blood. Now I think it was really stupid.

An array is a data type that contains or stores encoded values. Each encoded value is called an element of the array ), the encoding of each element is called index ).

Javascript is a magic scripting language, because it is a non-type language, so an array element can have any data type, different elements of the same array can also have different types, this clearly makes C language experts trigger blood three liters.

Create a JavaScript Array

In JavaScript, there are a total of the following methods to create an array:

1. Use the constructor array () of the array object to instantiate the array object with the new operator like creating an object (actually an object.

In this way, an array without elements is created, and the number of elements is null.

// Create an empty array
VaR arr = new array ();
// Its length is -- 0
Alert (ARR. Length );

2. Use the constructor array () to specify the first n elements of an array.

The length of the array created in this way is N, and the subscript of the array is from 0 to n-1.

// Create an array. The first seven digits are 'A', 'B', 'C', 'D', 1, 2, and 3.
VaR arr = new array ('A', 'B', 'C', 'D', 1, 2, 3 );
// The array length is 7.
Alert (ARR. Length );

3. Using the constructor new array (), add an integer directly as the parameter to specify the length of the array. Each element value of the created array is undefined.

// Specify the array length as 10
VaR arr = new array (10 );
Alert (ARR. Length );
// The array element is undefined.
Alert (ARR [0]);

What is the effect if I pass a negative number, zero, letter, or string?

// If no response is returned, array creation fails.
VaR arr = new array (-1 );

Alert (ARR. Length );
// The array length is 0.
VaR arr = new array (0 );

Alert (ARR. Length );
// If no response is returned, array creation fails.
VaR arr = new array ();

Alert (ARR. Length );
// Create an array with a length of 1 and only one string
VaR arr = new array ('A ');

Alert (ARR. Length + "arr [0]'s value is:" + arr [0]);

Er? After reading this, are you surprised? Why are we using the Array () constructor? It's so strange. And whether you want to use the constructor array () to create an array.

The following error occurs:

Array direct quantity

The direct amount of arrays allows you to directly embed the values of an array into a javascript program, just like introducing string text into nicknames to define a direct amount of strings.

To create an array directly, you only need to put a list of values separated by commasSquare brackets (brackets).

// Use the array directly to give an array and a friend list without full statistics.
// No particular ranking
VaR arr = ['xiaoxiaozi', 'laonb', 'bolo', '1t1g', 'zeric ', 'xiao Ming piao', 'porridge Bu', 'Wilderness '];
// The categories are different, but they are all what I eat this evening.
VaR foot = ['chicken soup stinky beance', 'Spicy tang', 'Ice factory', 'plum ', 'canned peach'];
// Example of a formal point
VaR magic_arr = [['prop sub', {ID: simaopig, age: 25}], [1, true, false], 'all types of data are available, and there are subarrays, haha '];

Read and Write operations on Arrays

Reading array elements is relatively simple. You only need to use square brackets (brackets.

Before talking about this, let's first recall what is used for object reading? That is, the "." operator. What else can be used? Well, that's the square brackets ". This tells us that arrays are actually objects. Well. They are essentially the same

An array has a lower mark, and its value range is an integer greater than or equal to 0 and less than 232-1. If the number is too large, JavaScript cannot be used. Because it will automatically convert it to a "string ".

In JavaScript, array elements are sparse, which means that the subscript of the array will not fall into a continuous number range. Only those elements actually stored in the array can be allocated internally, the rest will not waste your precious memory space.

// Define an array
VaR arr = new array (1, 2, 3, 4, 'A', 'B', 'C ');
// Read the array element. The subscript is in square brackets. Therefore, 2 is returned for this request.
Arr [1]
// Write the array element, 10, overwrite the fourth array element array to (, 'A', 'B', 'C ')
Arr [3] = 10;

For example, we define 0 and 1000 for the array. Only 0 and 1000 subscripts are allocated memory space, and the remaining 999 subscripts are not allocated internal space.

// Declare an empty array
VaR arr = new array ();
Arr [0] = 'xiaoxiaozi ';
Arr [1000] = 'simaopig ';
// 1001mm. From 0 to 1000
Alert (ARR. Length );
// No definition, undefined
Alert (ARR [999]);

Array Length

Use the "instance attribute" of "length" to obtain the array length in Javascript. If you are not clear about the concept of "instance attribute", I suggest you take a look at my previous log. Haha.

The subscript of the array starts from 0. Therefore, the maximum subscript of the array of n elements is n-1 and the length is N.

As we have mentioned above, the subscript of the array must be smaller than 232-1, which means that the maximum length of the Javascript array length is 232-1.

You can assign an object to an array element, but the object does not have the Length attribute. Therefore, the Length attribute is the most important feature of the array. Haha.

 

(From: http://blog.csdn.net/lifeng_beijing/archive/2007/06/17/1654882.aspx)

There is no concept of multi-dimensional array in JavaScript.

But it can be simulated.

1 dimension

// When the length of an array cannot be determined, declare an array name first and assign values one by one.
VaR tarray = new array ();
Tarray [0] = 'a ';
Tarray [1] = '2 ';

// 2 know the exact length and create an array
VaR tarray = new array (10 );

// 3 create an array and assign a value at the same time
VaR tarray = new array ('A', '2', '3', '4', '5', '6', '7', '8 ', '9', '10', 'J', 'Q', 'k ');

VaR tarray = ['A', '2', '3', '4', '5', '6', '7', '8', '9 ', '10', 'J', 'Q', 'K'];

// The following multi-dimensional arrays are also similar

2-Dimension

Method 1

VaR tarrar = new array ();
Tarrar [0] = new array ();

Tarrar [0] [0] = "AA ";

Tarrar [0] [1] = "BB ";

Tarrar [1] = new array ();
Tarrar [1] [0] = "cc ";
Tarrar [1] [1] = "DD ";

Method 2

VaR AA = new array (['1', '2'], ['3', '4'], ['5', '6']);

Dimension 3

Method 1

VaR tarray = new array ();
Tarray [0] = new array ();
Tarray [0] [0] = new array ();
Tarray [0] [1] = new array ();

Tarray [0] [0] [0] = "111 ";
Tarray [0] [0] [1] = "222 ";
Tarray [0] [1] [0] = "333 ";
Tarray [0] [1] [1] = "444 ";

Method 2

VaR AA = new array ([['000', '001', '002'], ['010 ', '011', '012'], ['020 ', '021 ', '022'], [['123456', '1234568', '1234568'], ['1234568', '1234568'], ['123', '123', '123']);

Note the [] nested position in the braces. To make it clearer. Modified the format.

VaR BB = new array (
[
['000', '001', '002'],
['012', '011', '012'],
['020', '021 ', '022']
],
[
['20160301', '20160301', '20160301'],
['20160301', '20160301', '20160301'],
['20160301', '20160301', '20160301']
]
);

 

(From: http://hi.baidu.com/jspboy/blog/item/7d6472cf55ab3938f8dc61af.html)

Shift: Delete the first entry of the original array and return the value of the deleted element. If the array is empty, undefined is returned.
VaR A = [1, 2, 3, 4, 5];
VaR B = A. Shift (); // A: [2, 3, 4, 5] B: 1

Unshift: add the parameter to the beginning of the original array and return the length of the array.
VaR A = [1, 2, 3, 4, 5];
VaR B = A. unshift (-2,-1); // A: [-2,-,] B: 7
Note: In ie6.0, the test return value is always undefined, and in ff2.0, the test return value is 7. Therefore, the return value of this method is unreliable. You need to use splice instead of this method when returning the value.

Pop: Delete the last entry of the original array and return the value of the deleted element. If the array is empty, undefined is returned.
VaR A = [1, 2, 3, 4, 5];
VaR B = A. Pop (); // A: [1, 2, 3, 4] B: 5

Push: add the parameter to the end of the original array and return the length of the array.
VaR A = [1, 2, 3, 4, 5];
VaR B = A. Push (6, 7); // A: [1, 2, 3, 4, 5, 6, 7] B: 7

Concat: returns a new array consisting of adding parameters to the original array.
VaR A = [1, 2, 3, 4, 5];
VaR B = A. Concat (6, 7); // A: [1, 2, 3, 4, 5] B: [1, 2, 3, 4, 5, 7]

Splice (START, deletecount, val1, val2,...): Delete the deletecount item from the start position, and insert val1, val2 ,...
VaR A = [1, 2, 3, 4, 5];
VaR B = A. splice (, 9); // A: [,] B: []
VaR B = A. splice (0, 1); // same as shift
A. splice (0, 0,-2,-1); var B = A. length; // same as unshift
VaR B = A. splice (A. Length-1, 1); // same as pop
A. splice (A. length, 7); var B = A. length; // same as push

Reverse: returns the reverse order of the array.
VaR A = [1, 2, 3, 4, 5];
VaR B = A. Reverse (); // A: [5, 4, 3, 2, 1] B: [5, 4, 3, 2, 1]

Sort (orderfunction): sorts arrays by specified parameters.
VaR A = [1, 2, 3, 4, 5];
VaR B = A. Sort (); // A: [1, 2, 3, 4, 5] B: [1, 2, 3, 4, 5]

Slice (START, end): returns a new array consisting of items from the original array that specify the start subscript to the end subscript
VaR A = [1, 2, 3, 4, 5];
VaR B = A. Slice (); // A: [, 5] B: [, 5]

Join (separator): A string is set up for the elements of the array. The separator is separator. If it is omitted, a comma is used as the Separator by default.
VaR A = [1, 2, 3, 4, 5];
VaR B = A. Join ("|"); // A: [1, 2, 3, 4, 5] B: "1 | 2 | 3 | 4 | 5"

 

An array is an internal object provided by JavaScript. It is a standard set. We can add (push), delete (shift) elements, we can also traverse the elements in the for loop, so can we have other sets in addition to arrays in JavaScript?

Because of the language features of JavaScript, We can dynamically add and delete attributes to common objects. Therefore, objects can also be seen as a special set of Js. The following compares the features of array and object:

Array:

New: var ary = new array (); or var ary = [];
Added: ary. Push (value );
Delete: delete ary [N];
Traversal: For (VAR I = 0; I <ary. length; ++ I) ary [I];

Object:

New: var OBJ = new object (); or var OBJ = {};
Added: OBJ [Key] = value; (Key is string)
Delete: delete OBJ [Key];
Traversal: For (var key in OBJ) OBJ [Key];

From the above comparison, we can see that the object can be used as a set. in the use of the popup window to create an infinitely webpage menu (3), I introduced the _ menucache __implemented by Eric __, it is also a simulated set object.

If we want to retrieve a specified value in array, We need to traverse the entire array:

  
Code:
VaR keyword =;
For (VAR I = 0; I <ary. length; ++ I)
{
If (ary [I] = keyword)
{
// Todo
}
}

 

However, to retrieve a specified key entry in an object, you only need to use:

  
Code:
Var key = '';
VaR value = OBJ [Key];
// Todo

This feature of the object can be used to efficiently retrieve the string set of unique. The time complexity of traversing the array is O (n), and the time complexity of traversing the object is O (1 ). Although the for search cost for 10000 sets is dozens of MS, if it is 1000*1000 queries or more, the advantages of using objects are shown. Before that, I made a mapping to map 100 unique characters to 1000 string arrays, which took 25-30 s! Later, I changed the for traversal to the member reference of the object simulation set. The same data volume mapping takes only 1.7-2 s !!!

For the collection traversal efficiency (from high to low): VaR value = OBJ [Key];> for (;)> for (in ). The worst efficiency is for (in). If the set is too large, do not use for (in) traversal.

 

I (LSL) want to emphasize this method:

 

VaR arr = [{name: "LSL", age: "24" },{ name: "kW", age: "23"}];

Alert (ARR [1] ["name"]);

 

 

 

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.