Array in JavaScript

JavaScript Arrays

An array is a special variable, which can hold more than one value:

Why Use Arrays?

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

An array can hold many values under a single name, and you can access the values by referring to an index number.

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

It is a common practice to declare arrays with the const keyword.

Learn more about const with arrays in the chapter: JS Array Const.

Читайте также:  Python кортеж типы элементов

Example

Spaces and line breaks are not important. A declaration can span multiple lines:

Example

You can also create an array, and then provide the elements:

Example

Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

Example

The two examples above do exactly the same.

There is no need to use new Array() .

For simplicity, readability and execution speed, use the array literal method.

Accessing Array Elements

You access an array element by referring to the index number:

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element

This statement changes the value of the first element in cars :

Example

Converting an Array to a String

The JavaScript method toString() converts an array to a string of (comma separated) array values.

Example

const fruits = [«Banana», «Orange», «Apple», «Mango»];
document.getElementById(«demo»).innerHTML = fruits.toString();

Access the Full Array

With JavaScript, the full array can be accessed by referring to the array name:

Example

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns «object» for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its «elements». In this example, person[0] returns John:

Array:

Objects use names to access its «members». In this example, person.firstName returns John:

Object:

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods:

Array methods are covered in the next chapters.

The length Property

The length property of an array returns the length of an array (the number of array elements).

Example

The length property is always one more than the highest array index.

Accessing the First Array Element

Example

Accessing the Last Array Element

Example

Looping Array Elements

One way to loop through an array, is using a for loop:

Example

const fruits = [«Banana», «Orange», «Apple», «Mango»];
let fLen = fruits.length;

You can also use the Array.forEach() function:

Example

const fruits = [«Banana», «Orange», «Apple», «Mango»];

Adding Array Elements

The easiest way to add a new element to an array is using the push() method:

Example

const fruits = [«Banana», «Orange», «Apple»];
fruits.push(«Lemon»); // Adds a new element (Lemon) to fruits

New element can also be added to an array using the length property:

Example

const fruits = [«Banana», «Orange», «Apple»];
fruits[fruits.length] = «Lemon»; // Adds «Lemon» to fruits

Adding elements with high indexes can create undefined «holes» in an array:

Example

const fruits = [«Banana», «Orange», «Apple»];
fruits[6] = «Lemon»; // Creates undefined «holes» in fruits

Associative Arrays

Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes.

Example

const person = [];
person[0] = «John»;
person[1] = «Doe»;
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return «John»

WARNING !!
If you use named indexes, JavaScript will redefine the array to an object.

After that, some array methods and properties will produce incorrect results.

Example:

const person = [];
person[«firstName»] = «John»;
person[«lastName»] = «Doe»;
person[«age»] = 46;
person.length; // Will return 0
person[0]; // Will return undefined

The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes.

In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.

  • JavaScript does not support associative arrays.
  • You should use objects when you want the element names to be strings (text).
  • You should use arrays when you want the element names to be numbers.

JavaScript new Array()

JavaScript has a built-in array constructor new Array() .

But you can safely use [] instead.

These two different statements both create a new empty array named points:

These two different statements both create a new array containing 6 numbers:

The new keyword can produce some unexpected results:

Источник

String Array in JavaScript

STRING ARRAY IN JAVASCRIPT

JavaScript support various types of array, string array is one of them. String array is nothing but it’s all about the array of the string. The array is a variable that stores the multiple values of similar types. In the context of a string array, it stores the string value only. The string is a combination of characters. Here are few examples of string – “RAM”, “SHYAM”, “XYZ”, “xyz” etc. There is nothing different from the array of string to the array of integers or the decimals. Almost all the functionality remains the same.

Web development, programming languages, Software testing & others

Type of Array in JavaScript with Example

There are two types of string array like integer array or float array.

1. Traditional Array

This is a normal array. In this, we declare an array in such a way the indexing will start from 0 itself. 0 will be followed by 1, 2, 3, ….n.

var in a key use to declare any variable. “characters” is the name of the array. AB, CD, XY are values stored in the array. In the example array declaration, we can access the value by places 0,1 and 2. Let’s see how we can access the value of the above-mentioned code.

     

Print Array of String Using for Loop:

     

The above code will alert all the values one by one.

2. String Array as An Object

This is a type of array that uses the object of key-value pairs.

Declaration:

This is a pair of array of key and value. If we want to use the 0 place value we can access this by using objectArray[0].

     

Using this approach we can assign any key not 0, 1, 2, etc. We can go for any string as well. Let’s see it with an example.

     

We can see we have used first and second for the 0 and 1 position key. The output remains the same as was in the previous example. To access first element value we will use objectArray[‘first’]).

Now, let’s see what will be the output of the below code:

     

Since there is no key with 0 is defined, the output of the above code will be undefined.

String Array in JavaScript-1.1

Function on A String Array

Function on A String Array is given below,

join() function

This will concatenate the string array element together with the specified separator. The below code will join the array elements with the pipeline operator (|).

  

The output of the above code will be – AB | CD | XY

concat() function

we can use this function to join two arrays.

  

The output of the above code will be – AB,CD,XY,AB,CD,XY

includes() function

This function will return the boolean value (true or false). If a specified string exists in an array then it will return true otherwise it will return false. Let’s see the same with an example.

  

split() function

this function will take the string as an input and will split that to the array. Let’s see the same with an example.

  

Conclusion

JavaScript support various types of array we can go for. We need not worry about the data type while using the JavaScript string array. We should include the array of string in our routine as a developer to deal with the coding kinds of stuff. String array we can use where we are not sure about kinds of data we will be stored at the run time. So, we can say that the string array in a hybrid array as it can combine various types of data value. Like we can store integers, characters or any other string.

Now, it’s time to test yourself

  • By default, the array indexing starts from 0. True or False?
  • In JavaScript need not to define the data type at the time of the Array declaration. True or False?
  • Most of the JavaScript array functions remains the same for String array. True or False?
  • Write a program in JavaScript to use the string function to get all string concatenated by the semicolon?

This is a guide to String Array in JavaScript. Here we discuss function and type of array in javascript with an example which includes traditional array, string array as an object. You may also look at the following articles to learn more –

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

JAVASCRIPT Course Bundle — 83 Courses in 1 | 18 Mock Tests
343+ Hours of HD Videos
83 Courses
18 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Оцените статью