Array creation in JavaScript

Source: Internet
Author: User

Array creation in JavaScript

An array is an ordered collection that contains an object or primitive type. It's hard to imagine what a program that doesn't use an array will look like.

Here are a few ways to manipulate arrays:

    1. Initialize the array and set the initial value

    2. Accessing array elements by index

    3. Add new Element

    4. Delete an existing element

This article covers the initialization of arrays and the operation of setting the initial values. The basic way to do this in JavaScript is to use an array literal, such as [1, 5, 8] an array constructor new Array (1, 5, 8) .

In addition to manual enumeration, JavaScript provides a more interesting and straightforward way to create arrays. Let me take a look at the general and advanced scenarios for initializing arrays in JavaScript.

1. Array literals

The array literal consists of a set [ ] of comma-separated elements wrapped in square brackets element1, element2, ..., elementN .

Let's look at a few examples of array literals:

View in JS Bin

let numbers = [1, 5, 7, 8];let planets = ['Earth', 'Mercury', 'Jupiter'];

An array literal can contain any type of element, including null , undefined primitive types, and objects:

View in JS Bin

let mixed = [1, 'Earth', null, NaN, undefined, ['Mars']];
1.1 comma in the array literal

Commas are , used to separate elements in the array literal. Arrays of different structures are created when a comma-based location or the absence of elements between commas.

Let's take a look at the existing three cases in detail.

The first case: normal array literals

Typically, there is an element between any pair of commas and the array literal does not start or end with a comma . This is the recommended way to manually initialize an array using a comma-delimited method:

View in JS Bin

let items = ['first', 'second', 'third'];items; // => ['first', 'second', 'third']

itemsis created by 2 comma-delimited 3 elements.

In this example item , there is a dense array, because its elements have successive indexes (or simply, there are no holes in the array).

Most of the time, you will initialize the array in this way.

Second case: a useless comma at the end of the array

The second case is similar to the first, except that the element is not specified after the last comma . In this case, the last comma is ignored by javascript:

View in JS Bin

let items = ['first', 'second', 'third', ];items; // => ['first', 'second', 'third']

‘third‘a comma specified after the element, which is the last comma in the array and does not have any elements after that. The comma at the end is useless, meaning it has no effect on the newly created array.

In this case, JavaScript also creates a dense array.

Third case: There are no elements between commas

The third case occurs when there is no specified element between a pair of commas or when the array literal begins with a comma .

This creates a sparse array: A set whose element index is not contiguous (in other words, there is an empty hole in the array).

The following array literal begins with a comma, creating a sparse array:

View in JS Bin

let items = [, 'first', 'second', 'third'];items;        // => [<1 empty slot>, 'first', 'second', 'third']items[0];     // => undefineditems[1];     // => 'first'items.length; // => 4

The array literal [, ...] begins with a comma. The result is items a sparse array, where the 0 index is an empty slot. Access to the empty slots items[0] will be obtained undefined .

It is important to differentiate between an empty slot and a value that is an undefined element. Access to this type of element by index is obtained undefined , which makes it tricky to differentiate them.

An empty slot means that the array has no element (return) at an index location index in array false , which undefined is different from the element ( index in array return) where a value is true .

It is important to note that the empty slots are displayed in the Firefox console <1 empty slot> , which is the correct way to show the empty slots. Chrome's console will show undefined x 1 . The console of the other browsers will simply be displayed undefined .

A sparse array is also created when there are no elements between the two commas of the array literal:

View in JS Bin

let items = ['first', , 'second', 'third'];items;        // => ['first', <1 empty slot> ,'second', 'third']items[0];     // => 'first'items[1];     // => undefineditems.length; // => 4

The array literal contains a comma with no elements in the middle: [... , , ...] . This item becomes a 1 sparse array with an empty slot at the index. Access to the empty slots items[1] will be obtained undefined .

Usually you should avoid this way of creating sparse arrays. Also, you should try not to manipulate sparse arrays as much as possible.

When you delete or add elements to an array literal, you may inadvertently create a sparse array. So remember to check carefully after the changes.

1.2 Spread operator Improvements

The spread operator introduced in ECMAScript 6 improves the initial new array using elements from other arrays.

In many scenarios, the spread operator makes it easier to create an array. The method is to prefix the array literal with the ... source array, and then the elements in the source array are included in the newly created array. It's so simple.

The following array literal was created with the spread operator:

View in JS Bin

let source = ['second', 'third'];let items = ['first', ...source];items; // => ['first', 'second', 'third']

The array literal [‘First‘, ...source] representation ‘First‘ is used as the first element in the array. The remaining elements are obtained from the array via the spread operator source .

The general enumeration of elements can be combined with the spread operator in an unrestricted manner.

View in JS Bin

let odds = [1, 3, 5];let evens = [4, 6];let zero = 0;let negative = -1;let items = [...odds, zero, ...evens, negative];items; // => [1, 3, 5, 0, 4, 6, -1]

Created items with a zero negative collection of source arrays and a combination of common variables and the predecessor spread ...odds operator ...evens .

Since the spread operator receives a normal, iterative object (the array is iterated by default), this makes the custom initialization possible.

A generator function also returns an iterative builder object, so you can create an array with the flexibility of the generator.

Let's create a first parameter that represents the element value the second parameter represents the number of elements in the generator function. It then initializes the new array with the spread operator and the array literal:

View in JS Bin

function* elements(element, length) {  let index = 0;  while (length > index++) {    yield element;  }}[...elements(0, 5)];    // => [0, 0, 0, 0, 0][...elements('hi', 2)]; // => ['hi', 'hi']

elements(element, length)a Generator object is created each time it executes. The spread operator uses the generator object to initialize the array.

[...elements(0, 5)]An array of 5 0 is created. Instead, an [...elements(‘hi‘, 2)] array of two strings is created ‘h1‘ .

2. Array constructors

The array in JavaScript is an object. Like any object, it has a constructor function that you can use to create a new instance Array . Let's look at an example:

View in JS Bin

// 构造器调用let arrayConstr = new Array(1, 5);arrayConstr;                        // => [1, 5]typeof arrayConstr;                 // => 'object'arrayConstr.constructor === Array;  // => true// 数组字面量let arrayLiteral = [1, 5];arrayLiteral;                       // => [1, 5]typeof arrayLiteral;                // => 'object'arrayLiteral.constructor === Array; // => true

arrayConstrand arrayLiteral are array instances, both of which are constructors Array . arrayConstrThe object is created through a constructor call: new Array(1, 5) .

You can also create an array instance by using array as you would call a normal function: Array(1, 5) .

You should be more inclined to use literals [item1, item2, ..., itemN] instead of constructors new Array(item1, item2, ..., itemN) to create arrays. The main reason is that the array literal is shorter and simpler. Another reason is that the array constructor produces strange behavior when the first parameter is a different type of value.

Let's take a look at Array how to create an array instance based on the type of the first parameter and the number of arguments.

Create a sparse array under a parameter of 2.1 numeric type

When the array constructor is new Array(numberArg) called with an argument of a single numeric type, JavaScript creates a sparse array of empty slots with the number specified by the parameter.

See an example:

View in JS Bin

let items = new Array(3);items;        // => [<3 empty slots>]items.length; // => 3

new Array(3)is a constructor call with a single argument 3 . A 3 sparse array of length is items created, but in fact it does not contain any elements but only a few empty slots.

This way of creating an array is of no value to itself. It is useful, however, to combine it with some static methods to create an array of the specified length and populate the generated elements.

2.2 Enumeration elements

If you Array pass in a parameter list instead of a single number when you call the constructor, these parameters become elements of the array.

This is almost the same way as the array literal, except in a constructor call.

The following example creates an array:

let items = new Array('first', 'second', 'third');items; // => ['first', 'second', 'third']

new Array(‘first‘, ‘second‘, ‘third‘)An array was created with the elements in the parameter.

Because of the flexibility of the spread operator, it is also possible to use elements from other arrays in a constructor call:

View in JS Bin

let source = new Array('second', 'third');let items = new Array('first', ...source);items; // => ['first', 'second', 'third']

new Array(‘First‘, ...source)The array is created with ‘First‘ elements and source all elements in the array.

Either way, you should be inclined to use the array literal as it is simpler and more straightforward.

2.3 Useful static methods

When you read about the part of creating a sparse array by passing in a number in a constructor call, you might wonder what the practical use is.

ECMAScript 6 adds some useful methods such as Array.prototype.fill() and Array.from() . Both of these methods can be used to populate an empty slot in a sparse array.

Let me use fill() the method to create an array containing 5 0:

View in JS Bin

let zeros = new Array(5).fill(0);zeros; // => [0, 0, 0, 0, 0]

new Array(5)A sparse array with 5 empty slots is created. fill(0)the method is then 0 filled with empty slots.

Static methods Array.from() have a wider usage scenario. Like the example above, let's create an array with 5 0:

View in JS Bin

let zeros = Array.from(new Array(5), () => 0);zeros; // => [0, 0, 0, 0, 0]

A new Array(5) number of sparse groups that are created by the length 5 as parameters are passed to Array.from() . The second parameter is returned as a 0 mapping function.

A total of 5 two iterations are performed, and the return value of the arrow function is used as an element of the array for each iteration.

Because mapping functions are executed in each iteration, it is possible to dynamically create array elements. Let's create an 1 array to include 5 :

View in JS Bin

let items = Array.from(new Array(5), (item, index) => index + 1);items; // => [1, 2, 3, 4, 5]

When a mapping function is called, two parameters are passed in: current item and current iteration index . The index parameter is used to generate the element: index + 1 .

Array.from()The first parameter can accept any object that can be iterated, which makes it more valuable.

Let's use a generator object to create an incrementing list of numbers:

View in JS Bin

function* generate(max) {  let count = 0;  while (max > count++) {    yield count;  }}let items = Array.from(generate(5));items;       // => [1, 2, 3, 4, 5]let itemsSpread = [...generate(5)];itemsSpread; // => [1, 2, 3, 4, 5]

generate(max)is a generator function that generates a number from a string 1 max .

Array.from(generate(5))A generator object is used as a parameter to create an 1 5 array containing the numbers.

[...generate(5)]the same purpose can be achieved using the spread operator and the array literal.

3. Summary

Array initialization is a common operation when working with collections. JavaScript provides a variety of methods and flexibility for this purpose.

The behavior of the array constructor can be a surprise to you in many cases. So the array literal is a better and simpler way to initialize an array instance.

It is a good choice when the array needs to be initialized based on the calculation of each iteration element Array.from() .

If the array element needs to be populated with the same value, use Array.prototype.fill() new Array(length) the and combination.

Do not underestimate the ability to iterate over objects and generator functions, which can be combined with the spread operator in the array literal or Array.from() in.

This article is reproduced from: Zhongcheng translation
Translator: Loveky
Links: http://www.zcfy.cc/article/713
Original: http://rainsoft.io/power-up-the-array-creation-in-javascript/

Array creation in JavaScript

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.