typescript

자바스크립트 8. 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리

JJIMJJIM 2020. 6. 22. 09:02
728x90
반응형
SMALL
자바스크립트 8. 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리 | 프론트엔드 개발자 입문편 (JavaScript ES6 )


- 한 배열안에는 동일한 타입의 데이터를 넣는 것이 중요

'use strict'

// Array

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

// 2. Index position
const fruits = ['apple', 'banana'];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);  > apple
console.log(fruits[1]);  > banan
console.log(fruits[2]);  > undefined
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 -> (callbackFn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
fruits.forEach(function(fruit, index, array) {
	console.log(fruit, index, array);
});
fruits.forEach((fruit) => console.log(fruit));

// 4. Addition, deletion, copy
// push: add an item to the end
push(...items: string[]): number
fruits.push('딸기', '복숭아');
console.log(fruits);

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

// add and item to the beginnning
fruits.unshift('딸기', '레몬');
console.log(fruits);

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

// note!! shift, unshift are slower than pop, push

// splice: remove an item by index position
fruit.push('딸기', '복숭아', '레몬');
console.log(fruits);
fruits.splice(1);   -> 지정한 인덱스부터 모든 데이터를 제거
console.log(fruits);
fruits.splice(1, 1); -> 지정한 인덱스부터 지정한 갯수만큼 제거
consoel.log(fruits);
fruits.splice(1, 1, '포도', '수박'); -> 제거를 지정한 자리에 지정한 데이터들이 들어간다.
console.log(fruits);

// combine two arrays
const fruits2 = ['1', '2'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

// 5. Searching
// find the index
// indexOf
console.clear();
console.log(fruits);
console.log(fruits.indexOf('apple')); -> 있으면 해당하는 item의 인덱스 번호, 없으면 -1
console.log(fruits.indexOf('3'));

// includes
console.log(fruits.includes('딸기')); -> 있으면 true, 없으면 false
console.log(fruits.includes('3'));

// LastIndexOf
console.log(fruits);
fruits.push('apple');
console.log(fruits.idnexOf('apple'));
console.log(fruits.lastIndexOf('apple'));












https://www.youtube.com/watch?v=yOdAVDuHUKQ

 

728x90
반응형
LIST