JavaScript

Array

김꼬알 2023. 6. 12. 16:37

배열 선언 방법

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

 

Index position

const fruits = ['apple', 'banana'];
console.log(fruits);    // ['apple', 'banana']
console.log(fruits.length);    // 2
console.log(fruits[0]);    // apple
console.log(fruits[1]);    // banana
console.log(fruits[2]);    // undefined
console.log(fruits[fruits.length - 1);    // banana -> 배열의 마지막 값 구하기

 

Looping over an array

  • 전체 배열의 값 출력하기
// for
for(let i = 0; i < fruits.length; i++ {
    console.log(fruits[i]);
    
// for of
for( let fruit of fruits) {
    console.log(fruits);
    
// forEach
fruits.forEach((fruit) => console.log(fruits));

 

Addition, deletion, copy

// push: add an item to the end
fruits.push('strawberry', 'peach');
console.log(fruits);    // ['apple', 'banana', 'strawberry', 'peach']

// pop: remove an item from the end
fruits.pop();
fruits.pop();
console.log(fruits);    // ['apple', 'banana']

// unshift: add an item to the beginning
fruits.unshift('strawberry', 'lemon');
console.log(fruits);    // ['strawberry', 'lemon', 'apple', 'banana']

// shift: remove an item from the beginning
fruits.shift();
console.log(fruits);    // ['lemon', 'apple', 'banana']

※ shift, unshift are slower than pop, push

 

// splice: remove an item by index position
fruits.push('strawberry', 'peach', 'lemon');
console.log(fruits);    // ['apple', 'banana', 'strawberry', 'peach', 'lemon']
fruits.splice(1, 1);    // fruits 배열의 1번 인덱스부터 1개 지우기
console.log(fruits);    // ['apple', 'strawberry', 'peach', 'lemon']
fruits.splice(1, 1, 'greenapple', 'watermelon';);    // fruits 배열의 1번 인덱스부터 1개 지우고 그 자리에 'greenapple', 'watermelon' 추가
console.log(fruits);    // ['apple', 'greenapple', 'watermelon', 'peach', 'lemon']

// combine two arrays
const fruits2 = ['pear', 'coconut'];
const newFruits = fruits.concat(fruits2);
console.log(fruits);    // ['apple', 'greenapple', 'watermelon', 'peach', 'lemon', 'pear', 'coconut']

 

Searching

// indexOf: find the index
console.log(fruits);    // ['apple', 'greenapple', 'watermelon', 'peach', 'lemon']
console.log(fruits.indexOf('apple'));    // 0
console.log(fruits.indexOf('watermelon'));    // 1
console.log(fruits.indexOf('coconut'));    // -1 -> 배열에 값이 없을 경우

// includes
console.log(fruits.includes('watermelon'));    // true
console.log(fruits.includes('coconut'));    // false

// lastIndexOf
fruits.push('apple');
console.log(fruits);    // ['apple', 'greenapple', 'watermelon', 'peach', 'lemon', 'apple']
console.log(fruits.indexOf('apple'));    // 0 -> 배열에서 같은 값이 여러개일 경우, 첫번째 인덱스를 알려줌
console.log(fruits.indexOf('apple'));    // 5 -> 배열에서 같은 값이 여러개일 경우, 마지막 인덱스를 알려줌

'JavaScript' 카테고리의 다른 글

JSON  (1) 2023.06.13
Array APIs  (0) 2023.06.12
Object  (1) 2023.06.09
class vs object  (0) 2023.06.08
Function, Arrow Function  (0) 2023.06.07