배열과 배열 메서드

wangjh789·2022년 8월 29일
0

javascript

목록 보기
12/12
post-thumbnail

유사객체

유사객체는 객체가 아니다.
length property를 가지고 있고, 인덱스와 인덱스로 접근할 item을 가지고 있다.
ex) NodeList, String

Array.from() 은 유사 배열 객체나 이터러블을 배열로 만들어준다.
const arr = Array.from('Hi!'); arr = ['H','i','!']
유사배열 객체는 for-of문을 사용할 수 없다.

const nodeLists = document.querySelectorAll('li');
console.log(nodeLists);

const nodeListArr = Array.from(nodeLists);
console.log(nodeListArr);

arr.push() 맨 뒤에 요소추가
arr.unshift() 맨 앞에 요소추가
배열 길이 반환

arr.pop() 맨 뒤 요소 삭제
arr.shitf() 맨 앞 요소 추가
삭제된 요소 반환

splice()

splice() -> 모든배열 조작이 가능하다.
arr.splice(0,0, ...items) -> 0번째 인덱스에 0개의 요소를 삭제하고 그 자리에 items를 넣겠다.
원하는 인덱스에 삭제하고, 삽입하는게 가능하다.

arr.splice(1) -> 인덱스1번에서 x개를 삭제하겠다.(0번 요소를 제외한 모든 요소가 삭제됨)

slice()

배열을 복사하는 메서드로 범위를 설정할 수 있다.

indexOf() 와 find()

indexOf()는 찾는 요소의 인덱스를 반환하는 메서드이다.
중요한 점은 찾는 요소가 기본 값일 때만 찾을 수 있다. (객체와 같은 참조형는 찾지 못한다.)
포함되어 있는지만 확인하려면 includes() 를 사용한다. (arr.indexOf() !== -1 과 같음)

find()함수는 인자로 익명함수를 넘긴다. 익명함수의 파라미터는 찾으려는 객체, 인덱스값, 전체 배열이다.
boolean을 통해 배열의 참조된 객체를 반환한다.
findIndex()는 비슷하지만 해당 객체의 인덱스를 반환한다는 점이다.

const personData = [{ name: 'Max' }, { name: 'Manuel' }];

const mamuel = personData.find((person, idx, persons) => {
  return person.name === 'Manuel';
});

forEach()

prices.forEach((price,idx,prices)=>{
})

for문을 사용해도 괜찮지만, 더 쉽게 인덱스에 접근할 수 있다는 장점이 있다.

map()

const temps = prices.map((price,idx,prices)=>{
  const temp = price*2;
  return temp;
})

prices 배열을 그대로 유지하고 모든 값을 2배로 올린 새로운 temps라는 배열을 생성한다.

sort()

const sortedTemps = temps.sort((a,b)=> {...})

내부 익명함수의 리턴값이 0보다 크다면 자리를 바꾼다.
내림차순의 경우 reverse()를 이용한다.

filter()

const fillteredTemps = temps.filter((temp,index,temps)=>{...})

내부 익명함수의 false인 경우 요소에서 빠지게 된다.

reduce()

const sum = prices.reduce((preValue,curValue,curIndex,prices)=>{
	return perValue+curValue;
},0);

0은 초기값을 의미한다.
첫번째 실행에서 preValue는 초기값(0), curValue는 0번째 요소를 의미한다.
그렇게 루프가 계속되면서 값은 누적되고 sum이 리턴된다.

배열내의 객체값을 복사할 때

const persons = [{name:'A',age:10},{name:'B',age:20}];

const copyPersons = persons.map(person=>({name:person.name, age:person.age});
profile
기록

0개의 댓글