본문 바로가기

JavaScript

[JavaScript] 8. 배열 제대로 알고 쓰자

1. Declaration

 

const arr1 = new Array();
const arr2 = [1, 2];

 

2. Index position

 

const fruits = ["a", "b"];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
console.log(fruits[fruits.length - 1]);

 

3. Looping over an array

print all fruits

// a. for
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// b. for of
for (let fruit of fruits) {
  console.log(fruit);
}

// c. forEach
fruits.forEach(function (fruit, index) {
  console.log(fruit, index);
});

// another
fruits.forEach((fruit) => console.log(fruit));

 

4. Addtion, deletion, copy

 

// push : add an item to the end
fruits.push("c", "d");
console.log(fruits);

// pop : remove an item from the end.
fruits.pop();
fruits.pop();
consol.log(fruits);

// unshift : add an item to the beginning
fruits.unshift("e", "f");

// shift : remove an item from the beginning
fruits.shift();
fruits.shift();
console.log(fruits);

// note!! shift, unshift 는 push, pop 보다 너무 느리다.
// splice: remove an item by index position
fruits.push("e", "f", "i");
console.log(fruits);

fruits.splice(1, 1);
console.log(fruits);

fruits.splice(1, 1, "u", "m");
console.log(fruits);

//combine two arrays
const fruits2 = ["r", "b"];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

 

5. Searching

find the index

 

console.clear();
console.log(fruits);

//indexOf
console.log(fruits.indexOf("n"));

//includes
console.log(fruits.includes("p"));

// lastIndexOf
console.clear();
fruits.push("n");
console.log(fruits);
console.log(fruits.indexOf("g"));
console.log(fruits.lastIndexOf("n"));