ARRAYS IN JAVASCRIPT


ARRAY:

  • Array allows us to store multiple values in a single variable.
  • Array values are accessed using index variables(also called as subscripts).
  • Can have single,two ,three dimensions etc.
  • Single dimension refers to rows
  • Multiple dimensions refers to both rows and columns.

SYNTAX:

var array-name = [item1, item2, ...]; 

Example:

var a=[“apple”,”mango”,”grapes”];
(or)
var a = new Array("apple", "mango", "grapes");
Accessing the elements of an array:
An array element can be accessed by using index value.

Example:

var name = a[0];
In this example first element of the array is stored in the variable called 'name'

Example:

a[0] = "PineApple";
This example modifies the arrays first element into Pineapple instead of apple.

Tip:

[0] is the first element in an array. [1] is the second. Array indexes start with 0.

NEW KEYWORD:

Following example also creates an Array, and assigns values to it:
var a = new Array("apple", "mango", "grapes");

LOOPING ARRAY ELEMENTS:

  • The best way to access the elements of an array is by using LOOP.
  • The best Loop to use is FOR-NEXT

Example:

var index;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
    text += fruits[index];
}

Arrays are objects:

  • Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
  • Arrays use numbers to access its "elements"
  • Objects use names to access its "members"

Example:

var person = ["sakthi", "vel", 34];
person[0] returns sakthi

Example:

var person = {firstName:"sakthi", lastName:”vel", age:34};
person.firstName returns sakthi

Array properties:

  • constructor-Returns a reference to the array function that created the object.
  • input-This property is only present in arrays created by regular expression matches.
  • index-This property represents the zero-based index of the match in the string
  • length-Reflects the number of elements in an array.

Array Methods:

  • concat()-Returns a new array comprised of this array joined with other array(s) and/or value(s).
  • every()-Returns true if every element in this array satisfies the provided testing function.
  • filter()-Creates a new array with all of the elements of this array for which the provided filtering function returns true.
  • sort()-Sorts the elements of an array.
  • reverse()-Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
  • join()-Joins all elements of an array into a string.
  • indexOf()-Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
  • push()-Adds one or more elements to the end of an array and returns the new length of the array.
  • pop()-Removes the last element from an array and returns that element.


No comments:

Post a Comment