[JS] Javascript #7 Summary

1 minute read

Javascript #7 Summary


Array

  • 비슷한 종류의 데이터 (object) 를 묶어서 한 곳에 보관하는 것: Data Structure (자료구조)

  • Javascript === dynamically typed language
    ==> 여러가지 type 의 데이터를 묶어서 보관 가능하지만 권장 X



Declaration

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


Index Position

const fruits = ['🍎', '🍌'];

console.log(fruits.length);  // 2
console.log(fruits[0]);  // 🍎
console.log(fruits[1]);  // 🍌
console.log(fruits[2]);  // undefined
console.log(fruits[fruits.length-1]);  // 🍌



Looping over an array

print all fruits

for

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

for of

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

forEach

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



Addition, Deletion, Copy

  • push

  • pop

  • unshift

  • shift

note: shift, unshift are slower than pop, push (배열의 길이가 길수록 더 느려진다.)

const fruits = ['🍎', '🍌'];

fruits.push('🍓', '🍑');  // add an item to the end
fruits.pop();  // remove an item from the end

fruits.unshift('🍇', '🍋');  // add an item from the beginning
fruits.shift();  // remove an item from the beginning


splice

  • remove an item by index position
const fruits = ['🍓', '🍑', '🍋', '🍇'];

fruits.splice(1);  // index 1 부터 전부 제거
fruits.splice(1, 1);  // index 1 부터 한개 제거
fruits.splice(1, 1, '🍏', '🍉');  // index 1 부터 한개 제거 후 해당 자리에 '🍏', '🍉' 삽입



Combine two arrays

const fruits = ['🍓', '🍑', '🍋', '🍇'];
const fruits2 = ['🥝', '🍒'];
const newFruits = fruits.concat(fruits2);

console.log(newFruits);

>>> ['🍓', '🍑', '🍋', '🍇', '🥝', '🍒']



Searching

  • indexOf

  • includes

  • lastIndexOf

const fruits = ['🍓', '🍑', '🍋', '🍇'];


// indexOf
console.log(fruits.indexOf('🍓'));  // 0
console.log(fruits.indexOf('🍋'));  // 2
console.log(fruits.indexOf('🌽'));  // -1

// includes
console.log(fruits.includes('🍋'));  // true
console.log(fruits.includes('🌽'));  // false
const fruits = ['🍓', '🍓', '🍓', '🍑', '🍋', '🍇'];

// lastIndexOf
console.log(fruits.indexOf('🍓'));  // 0
console.log(fruits.lastIndexOf('🍓'));  // 2

Leave a comment