Масив в JS

Масивът се използва за съхраняване на колекция от данни

### Декларация

let arr = new Array();
let arr = [];
// There are two syntaxes for creating an empty array
let fruits = ["Apple", "Orange", "Plum"]; 
alert( fruits[0] ); // Apple
alert( fruits[1] ); // Orange 
alert( fruits[2] ); // Plum

### Типове масиви

  • Хомогенни масиви
  • Разнородни масиви
  • Многомерни масиви
  • Назъбени масиви

### Хомогенни масиви

let array = ["Matthew", "Simon", "Luke"];
let array = [27, 24, 30];
let array = [true, false, true];

### Хетерогенни масиви

let array = ["Matthew", 27, true];

### Многоизмерни масиви

let array = [["Matthew", "27"], ["Simon", "24"], ["Luke", "30"]];

### Назъбени масиви

let array = [
    ["Matthew", "27", "Developer"],
    ["Simon", "24"],
    ["Luke"]
];

Някакъв важен метод в Array

### дължина

let fruits = ['Apple', 'Banana']

console.log(fruits.length)
// 2

### натискане

let fruits = ['Apple', 'Banana']
fruits.push('Orange')
// ["Apple", "Banana", "Orange"]

### поп

let last = fruits.pop() // remove Orange (from the end)
// ["Apple", "Banana"]

### смяна

let first = fruits.shift() // remove Apple from the front
// ["Banana"]

### unshift

fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"]

### indexOf

fruits.push('Mango')
// ["Strawberry", "Banana", "Mango"]

let pos = fruits.indexOf('Banana')
// 1

### парче

let fruits = [“Banana”, “Orange”, “Lemon”, “Apple”, “Mango”];
let citrus = fruits.slice(1, 3);
console.log(citrus);
// Orange,Lemon

### снаждане

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
// Banana,Orange,Lemon,Kiwi,Mango

### findIndex

function isOdd(element, index, array) {
  return (element%2 == 1);
}

console.log([4, 6, 7, 12].findIndex(isOdd));
// 2

### се присъединете

var a = [1, 2, 3, 4, 5, 6];
console.log(a.join());
// 1, 2, 3, 4, 5, 6

### намиране

function isOdd(element, index, array) {
  return (element%2 == 1);
}

console.log([4, 5, 8, 11].find(isOdd));
// 5

### concate

let num1 = [11, 12, 13],
    num2 = [14, 15, 16],
    num3 = [17, 18, 19];
console.log(num1.concat(num2, num3));
// [11,12,13,14,15,16,17,18,19]

### филтър

function isEven(value) {
  return value % 2 == 0;
}

let filtered = [11, 98, 31, 23, 944].filter(isEven);
console.log(filtered);
// [98,944]

### обратно

let arr = [34, 234, 567, 4];
console.log(arr);
let new_arr = arr.reverse();
console.log(new_arr);
// 34, 234, 567, 4
// 4, 567, 234, 34

### сортиране

let arr = [2, 5, 8, 1, 4]
console.log(arr.sort());
// 1,2,4,5,8

### за всеки

const items = [1, 29, 47];
const copy = [];

items.forEach(function(item){
  copy.push(item*item);
});
console.log(copy);
// 1,841,2209

### lastIndexOf

console.log([1, 2, 3, 4, 5].lastIndexOf(2));
// 1
console.log([1, 2, 3, 4, 5].lastIndexOf(9));
// -1