본문 바로가기

JavaScript

JS 배열 정리하고 가기.

배열 만들기

let fruits = ['사과' , '바나나']

consloe.log(fruits.length) // 2
// 인덱스 이용 접근
let first = fruits[0]; //사과

let last = fruits[fruits.length -1] // 바나나

// push()
let newLength = fruits.push('오렌지') // ["사과", "바나나", "오렌지"]

// pop() 마지막요소 제거
let last = fruits.pop() // 마지막 요소 제거 ["사과", "바나나"]

// shift() 맨앞 요소 제거
let first = fruits.shift() // ["바나나"]

// unshift 맨앞에 추가
let newLength = fruits.unshift('딸기') // ["딸기", "바나나"]

// indexOf() 특정 학목의 인덱스 찾기
fruits.push('망고') // ["딸기", "바나나", "망고"]

let pos = fruits.indexOf("바나나") // 1

// splice() 인덱스 위치에 있는 항목 제거
let removedItem = fruits.splice(pos, 1) // ["딸기", "망고"]

// splice(pos, n) pos 위치부터 n개의 항목을 제거함.
let vegetables = [ '양배추', '순무', '무', '당근']

let pos = 1, let n = 2
let removedItems = vegetables.splice(pos, n)
console.log(vegetables) // ["양배추", "당근"] 원본 배열의 값도 변한다 !
console.log(removedItems) // ["순무", "무"]

얕은 복사 Array.from() 메서드는 유사 배열 객체(array-like object)나 반복가능한 객체(iterable object)를 얕게 복사해 새로운 Array 객체를 만듭니다.

console.log(Array.from('foo')) // Array ["f", "o", "o"]

console.log(Array.from([1,2,3], x => x + x)); // Array [2, 4, 6]

Array.from() example

Array.from(arrayLike[ , mapFn[ , thisArg]])

Array.from('foo');
// ["f", "o", "o"]

const s = new Set(['foo', window]);
Array.from(s);
// ["foo", window]

const m = new Map([1,2], [2,4], [4,8]]);
Array.from(m);
// [[1,2] ,[2,4], [4,8]]

const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b']

Array.prototype.concat()

array.concat([value[ , value2[ , ... [, valueN]]])

concat() 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.

- 기존 배열을 변경하지 않습니다.

- 추가된 새로운 배열을 반환합니다.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

consloe.log(array3); // ['a', 'b', 'c', 'd', 'e', 'f']

Array.prototype.copyWithin

arr.copyWithin(target[ , start[ , end]])

const array1 = ['a', 'b', 'c', 'd', 'e'];

console.log(array1.copyWithin(0, 3, 4
// ["d", "b", "c", "d", "e"]

console.log(array1.copyWithin(1, 3));
// {"d", "d", "e", "d", "e"]

Array.prototype.entries()

arr.entires()

entries() 메서드는 배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 Array Iterator 객체를 반환합니다.

const array1 = ['a', 'b', 'c'];

const iterator1 = array1.entries();

console.log(iterator1.next().value); // Array [0, "a"]
console.log(iterator1.next().value); // Array [1, "b"]

Array.prototype.filter()

arr.filter(callback(element[ , index[ , array]])[ , thisArg])

callback : 각 요소를 시험할 함수. true를 반환하면 요소를 유지, false를 반환하면 버립니다.

  element : 처리할 현재 요소

  index : 처리할 현재 요소의 인덱스

  array : filter를 호출한 배열.

thisArg : callback을 실행할 때 this로 사용하는 값.

const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

const filterItems = (query) => {
	return fruits.filter((el) => el.toLowerCase().indexOf(query.toLowerCase()) > -1
	);
}

console.log(filterItems('ap')); // ['apple', 'grapes']

Array.prototype.flat()

const newArr = arr.flat([depth])

중첩 배열 구조를 평탄화할때 사용할 깊이 값 / 기본 값은 1입니다.

const arr1 = [1, 2, [3,4]];
arr1.flat(); // [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat(); // [1,2,3,4,[5,6]]

Array.prototype.forEach()

arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])

const items = ['item1', 'item2', 'item3'];
const copy = [];

// 이전
for (let i = 0; i<items.length; i++) {
	copy.push(items[i]);
}

// 이전
items.forEach(function(item) {
	copy.push(item);
});

'JavaScript' 카테고리의 다른 글

Component keywords [React]  (0) 2020.07.27
node / express 공부기.  (0) 2020.04.25
JS 문자열 메서드 훑고 가기.  (0) 2020.04.24
You Don't Know Node / translate  (0) 2020.04.22
var / let / const 간단정리  (0) 2020.04.22