Common JavaScript Manual/Data types - Arrays

Making Array

edit

For making array it's better to use list literal because it's most popular and simple syntaxis

a = []; //Empty list
b = [1,2,3,4,5]; //List with 5 elements

Work with elements

edit

And so, we have an array 'b' with five numbers and the empty array 'a'.

a[0] = b[2]; //1
delete b[2]; //2
b[3] = 6; //3
  1. From array b - [1,2,3,4,5] get element with index 2 (Numeration in arrays starts from 0). Now array a = [2]
  2. We delete element with index 2 from array b. Now array b = [0,1,undefined,3,4].
  3. We change value of element with index 3 from array b. Now array b = [0,1,undefined,6,4].

Work with slices

edit

Array.slice(start,end) - returns array with elements of Array from start index to end index without element with index end.

a = [0,1,2,3,4,5,6,7];
b = a.slice(2,5); //2,3,4

If start or end is negative number then index of start or end equal (length of array + start or end).

a = [0,1,2,3,4,5,6,7];
b = a.slice(2,-2); //2,3,4,5 because length = 8 and 8 + (-2) = 6

Array.splice(start,number,elem...) - return slice with number of elements from Array from start and it deletes this elements from Array, and it replaces it's by elem

a = [0,1,2,3,4,5,6,7];
b = a.splice(2,3,0,1,0);
print(b); // 2,3,4
print(a); // 0,1,0,1,0,5,6,7

Stack and row

edit

You can use any Array as stack or row for it there are 4 function.

Name Action
Array.pop() Delete and return last element of Array
Array.push(elem...) Insert elem to end of Array
Array.shift() Delete and return first element of Array
Array.unshift(elem...) Insert elem to start of Array

For example:

Foo = [1,2,3,4,5];
Bar = Foo.pop(); //Bar = 5 , Foo = [1,2,3,4]
Foo.unshift(Bar); // Foo = [5,1,2,3,4]

Sorting and reverse

edit

Also Array.sort([predicate]) - If predicate not defined then sort elements in Array in lexicographical order else sort element in Array by results of function predicate that gets two arguements and returns -1 if first argument less then second or 1 if second argument less then first or 0 if arguments equal.

Array.reverse() - reverse elements in Array

arr = [5,3,1,4,2];
arr.sort();
print(arr); //1,2,3,4,5
arr.reverse();
print(arr); //5,4,3,2,1

Concatenate and joining

edit

Array.concat(elem1...) - returns array that containg elements from Array and elem if elem[n] is array then to the array that returns are added all elements from elem[n].

Array.join([separator]) - returns string with all elements and separator before every, if separator not defined then separator = ","

arr1 = [0,1,2,3,4]
arr2 = [5,6,7,8,9]
elem = 10;
arr = arr1.concat(arr2,elem); //0,1,2,3,4,5,6,7,8,9,10
str = arr.join(';'); //0;1;2;3;4;5;6;7;8;9;10
print(str);

Length of Array

edit

Array.length - number of elements in Array

arr = [0,1,2,3,4,5]
print(arr.length); // 6


Data types - Numbers · Data types - Strings