JS/[드림코딩] 엘리 (완)

08강. Array

web_seul 2020. 7. 11. 14:02
반응형

JS = dynamically typed language

 

1. Declaration

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

 

2. Index position

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

console.log(fruits);			//['🍎',''];
console.log(fruits.length);		//2
console.log(fruits['key']);		//key에 상응하는 value 받음
console.log(fruits[0]);			//🍎
console.log(fruits[1]);			//🍌
console.log(fruits[2]);			//undefined
console.log(fruits[fruits.length-1]);	//마지막 요소

console.clear();

3. Looping over an array

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

//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, array){
    console.log(fruit, index, array); //🍎 0 ["🍎","🍌"]  🍌 0 ["🍎","🍌"]
});

//간략히_arrow함수
fruits.forEach((fruit)=> console.log(fruit));

 

4. Addition, delation, copy

push : add an item to the end

pop : remove an item from the end

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


fruits.push('🍓','🍑');
console.log(fruits); //["🍎", "🍌", "🍓", "🍑"]

fruits.pop('🍑');
console.log(fruits); //["🍎", "🍌", "🍓"]

fruits.pop('🍓');
console.log(fruits); //["🍎", "🍌"]

unshift : add an item to the beginning

shift : remove an item from the beginning

const fruits = ["🍎","🍌"]


fruits.unshift('🍓','🍑') ;
console.log(fruits); //["🍓","🍑","🍎","🍌"]

fruits.shift();
console.log(fruits); //["🍑","🍎","🍌"]

fruits.shift();
console.log(fruits); //["🍎","🍌"]

 

note!!

shift, unshft are slower than pop,push

 

splice : remove an item by index position

const fruits = ["🍎", "🍌"]


fruits.push('🍓','🍑','🍋');
console.log(fruits); 	//["🍎", "🍌", "🍓", "🍑", "🍋"]

fruits.splice(1);
console.log(fruits); 	//["🍎"] index만 설정할 경우 1이후 뒷쪽 데이터를 모두 삭제함

fruits.splice(1,1);
console.log(fruits); 	//["🍎", "🍓", "🍑", "🍋"] 1번 index부터 하나만 지움

fruits.splice(1,1,'🍏','🍉');
console.log(fruits); 	//["🍎", "🍏", "🍉", "🍑", "🍋"] // index1인 🍓를 지우고 🍏,🍉삽입

concat : combine two arrays

const fruits = ["🍎", "🍏", "🍉", "🍑", "🍋"]
const fruits2 = ['🍐','🥥'];

const newFruits = fruits.concat(fruits2);
console.log(newFruits); //["🍎", "🍏", "🍉", "🍑", "🍋","🍐","🥥"]

 

console.clear();

 

5. Searching

indexOf : find the index

const fruits = ["🍎", "🍏", "🍉", "🍑", "🍋"]

console.log(fruits.indexOf('🍎')); //0  찾는 사과가 몇번째 배열인지
console.log(fruits.indexOf('🍉')); //2
console.log(fruits.indexOf('🥝')); //-1 없는값을 찾은경우

includes

console.log(fruits.includes('🍉')); //true 수박이 배열에 포함되어있는지 T/F
console.log(fruits.includes('🥝')); //false

 

console.clear();

lastIndexOf

fruits.push('🍎'); 

console.log(fruits); //["🍎", "🍏", "🍉", "🍑", "🍋","🍐","🥥","🍎"]
console.log(fruits.indexOf('🍎')); //0 첫번째값 호출
console.log(fruits.lastIndexOf('🍎')); //7 마지막값 호출

 

반응형

'JS > [드림코딩] 엘리 (완)' 카테고리의 다른 글

10강. JSON  (0) 2020.07.20
09강. Array APIs  (0) 2020.07.20
07강. object  (0) 2020.07.05
06강. class vs object, 객체지향 언어 클래스 정리  (0) 2020.07.02
05강. Arrow function, 함수의 선언과 표현  (0) 2020.07.01