Thursday, 30 May 2024

Java Script: Arrays

 Arrays are container-like values that can hold other values. The values inside an array are called elements.

var myArray = [Balaji, 'is', 'Techno'];

Array elements don’t all have to be the same type of value. Elements can be any kind of JavaScript value — even other arrays.

EXAMPLE:

var student = [100, "Balaji", [20, "year"], false];

student;

OutPut

100,Balaji,20,year,false


Accessing Elements

To access one of the elements inside an array, you’ll need to use the brackets and a number like this: myArray[3]. JavaScript arrays begin at 0, so the first element will always be inside [0].

EXAMPLE:

var name = ["Balaji", "Tech"];

name[0];

OutPut

Balaji


To get the last element, you can use brackets and `1` less than the array’s length property.


 EXAMPLE:

var actors = ["Rajani", "Modi", "Amitab"];

actors[actors.length - 1];

OutPut

Amitab

This also works for setting an element’s value.


EXAMPLE:

var colors = ["red", "yelowww", "blue"];

colors[1] = "yellow";

colors;

OutPut

red,yellow,blue


Properties and methods

Arrays have their own built-in variables and functions, also known as properties and methods. Here are some of the most common ones.

length

An array’s length property stores the number of elements inside the array.


EXAMPLE:

["a", "b", "c", 1, 2, 3].length;

OutPut

6


concat

An array’s concat method returns a new array that combines the values of two arrays.


EXAMPLE:

["My name"].concat(["Balaji", "Tech"]);

OutPut

My name,Balaji,Tech


pop

An array’s pop method removes the last element in the array and returns that element’s value.


EXAMPLE:

["Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"].pop();

OutPut

Pluto


push

An array’s push method adds an element to the array and returns the array’s length.


EXAMPLE:

["John", "Kate"].push(83);

OutPut

3


reverse

An array’s reverse method returns a copy of the array in opposite order.


EXAMPLE:

["x", "y", "z"].reverse();

OutPut

z,y,x



No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts