배열의 메서드를 사용하려면 배열.메서드이름()으로 사용해야 한다.
배열.indexOf(인자)로 사용하고,
소괄호()안에 인자를 받아서 배열에서 같은 값이 있으면 그 인덱스를 반환한다. 없다면 -1을 반환한다.
let a = ['wecode','study','javascript','js']
// index 0 1 2 3
console.log(a.indexOf('study')) // 1
console.log(a.indexOf('java')) // -1
중복된 값이 있다면 먼저 나오는 인덱스를 반환한다.
let a = ['wecode', 'js', 'study','javascript','js']
// index 0 1 2 3 4
console.log(a.indexOf('js')) // 1
배열의 일부를 뽑아내는 메서드.
배열.slice(start, end)로 사용한다.
start에는 뽑아낼 배열의 시작 인덱스를 넣고,
end에는 마지막 인덱스의 바로 뒤 인덱스를 넣는다.
let a = ['wecode','study','javascript','js']
// index 0 1(start) 2 3(end)
console.log(a.slice(1,3)) // [ 'study', 'javascript' ]
console.log(a.slice(1)) // ['study', 'javascript', 'js']
console.log(a.slice(null,1)) // ['wecode']
start나 end를 생략가능한데, end를 생략하면 start 인덱스부터 배열을 뽑아낸다.
start를 생략하려면 falsy값을 넣어주면 되는데, end인덱스의 전까지 배열을 뽑아낸다. null대신에 0, [], NaN, Number 아무거나 적어도 falsy값으로 인식한다.
console.log(a) // [ 'wecode', 'study', 'javascript', 'js' ]
기존 배열a는 바뀌지 않고, 새로운 배열을 반환한다.
배열의 값을 채워주는 메서드.
배열.fill(value, start, end)로 사용한다.
value에는 채워넣은 값을 넣고, start와 end를 생략할 수도 있다.
start에는 채우기 시작할 요소의 인덱스,
end에는 채워넣을 요소의 마지막 인덱스의 바로 뒤 인덱스를 넣는다.
let a = ['wecode', 'study','javascript','js']
console.log(a.fill(0)) // [ 0, 0, 0, 0 ]
console.log(a) // [ 0, 0, 0, 0 ]
기존 배열 a가 바뀐다!
let a = ['wecode', 'study','javascript','js']
console.log(a.fill(0, 1, 2)) // [ 'wecode', 0, 'javascript', 'js' ]
// 인덱스를 음수로 넣는 경우
let a = ['wecode', 'study','javascript','js']
console.log(a.fill(0, -4, -2)) // [ 0, 0, 'javascript', 'js' ]
배열을 수정하는 메서드.
배열.splice(start,delete,add)로 사용한다.
start에는 역시 시작 인덱스를 넣고, delete와 add를 생략할 수도 있다.
delete에는 삭제할 요소의 갯수를 넣는다.
add에는 추가할 요소를 적는다. 다양한 데이터 타입이 가능하다.
splice메서드는 삭제되는 요소를 반환한다.
let a = ['wecode','study','javascript','js']
console.log(a.splice(1,2,'prestudy','vanilla'))
// [ 'study', 'javascript' ]
console.log(a) // [ 'wecode', 'prestudy', 'vanilla', 'js' ]
기존 배열a가 바뀐다.
let a = ['wecode', 'study','javascript','js']
console.log(a.splice(1)) // ['study', 'javascript', 'js']
delete와 add를 생략한다면 slice메서드와 똑같이 작동한다.
조건에 맞는 배열만 따로 뽑아내는 메서드.
배열.filter(조건 함수)로 사용한다.
조건 함수는 따로 밖에서 선언해준 함수를 쓸 수도 있고, filter 메서드 안에서 직접 작성하는 것도 가능하다.
let a = ['wecode','study','javascript','js']
1. 밖에서 함수 선언하고 사용
function filterArray(value) {
if (value.includes('j')) {
return value
}
}
console.log(a.filter(filterArray)) // [ 'javascript', 'js' ]
위의 함수와 아래 함수가 같은 개념이다.
for 반복문이 하는 일, 배열의 요소 하나씩 함수에 던져주는 일을 filter 메서드가 해주고 있다. filter 메서드가 최종으로 반환하는 새로운 배열은 newA 배열이라고 생각하면 된다.
function filterArray() {
let newA = []
for (let i=0; i<a.length; i++) {
if (a[i].includes('j')) {
newA.push(a[i])
}
}
return newA
}
2. filter 메서드 안에서 함수 작성
console.log(a.filter((value) => value.includes('j')))
// [ 'javascript', 'js' ]
console.log(a) // [ 'wecode', 'study', 'javascript', 'js' ]
조건에 맞는 배열만 반환하고, 기존 배열은 바뀌지 않는다.
배열을 붙이는 메서드.
앞배열.concat(뒷배열)로 사용한다.
뒷배열에는 여러 개의 변수 및 배열이 올 수 있다.
혼란스러운 점이.. 뒷배열 부분에 1,2로 값을 넣거나 [1,2]로 값을 넣는게 동일하게 작동한다. => MDN에 설명이 있었다!
'concat은 메서드를 호출한 배열 뒤에 각 인수를 순서대로 붙여 새로운 배열을 만듭니다. ¹인수가 배열이면 그 구성요소가 순서대로 붙고, ²배열이 아니면 인수 자체가 붙습니다. ³중첩 배열 내부로 재귀하지 않습니다.'
[1,2]로 추가하고 싶다면 [[1,2]]로 적어야 한다.
let a = ['wecode','study','javascript','js']
let b = ['Jenny', 'Jane']
let c = [1, 2]
console.log(a.concat(b))
// [ 'wecode', 'study', 'javascript', 'js', 'Jenny', 'Jane' ]
console.log(a.concat(b, c))
// [ 'wecode', 'study', 'javascript', 'js', 'Jenny', 'Jane', 1, 2 ]
console.log(a.concat(1 , 2))
// ²[ 'wecode', 'study', 'javascript', 'js', 1, 2 ]
console.log(a.concat([1 , 2]))
// ¹[ 'wecode', 'study', 'javascript', 'js', 1, 2 ]
console.log(a.concat(1 , [1, 2]))
// [ 'wecode', 'study', 'javascript', 'js', 1, 1, 2 ]
console.log(a.concat([[1 , 2]]))
// ³[ 'wecode', 'study', 'javascript', 'js', [ 1, 2 ] ]
기존 배열은 바뀌지 않는다.
const array = Array.from({length: 4}, () => Array(2).fill(null))
// array[4][2]
// ┌─────────┬──────┬──────┐
// │(index) │ 0 │ 1 │
// ├─────────┼──────┼──────┤
// │ 0 │ null │ null │
// │ 1 │ null │ null │
// │ 2 │ null │ null │
// │ 3 │ null │ null │
// └─────────┴──────┴──────┘
아..! 연주님 concat에 대해 혼돈하시는 부분 조금 알 것 같아요! 변수 a와 변수 b 모두 배열이잖아요? 두 개의 배열을 합치면 하나의 배열이 되는 것이 곧 concat 메서드이기 때문에 변수 a 와 [1, 2] 배열을 합쳐 하나의 배열이 된 게 아닐까요? (1, 2)를 concat하는 것은 [1]과 [2]처럼 요소를 하나만 갖는 배열들을 합쳐주는 것이구요!