S1U9 배열 정리

이유정·2022년 9월 5일
0

코드스테이츠 TIL

목록 보기
11/62
post-thumbnail

배열을 잘 다루기 위해서는 배열의 요소를 추가 변경, 삭제하는 방법을 잘 알아야 한다.
따라서, 배열에 사용할 수 있는 다양한 메서드를 알고 활용할 수 있어야 한다.

알아갈 메서드()
split(), join(), slice(), splice(), Array.isArray(), push(), unshift(), pop(), shift(), indexOf(), includes()

chapter1-1. 배열 기초

  • fruits 의 3번째 인덱스의 값은?
    : fruits[2]

  • 이차원 배열
    myNumber의 1번째 인덱스의 0번째 인덱스는?
    myNumber[1][0]

  • let myNumber = [[13, 30], [73, 8], [44, 17]]
    myNumber = [Array(2), Array(2), Array(2)]

  • index : 배열 안 요소의 순서값
    element : 배열 안 요소
    method
    . 을 사용하여 그 속성에 접근할 수 있음

  • 배열로 할 수 있는 것 :
    1) 길이를 알 수 있음
    let myNumber =[73, 98, 86, 61]
    myNumber.length; //4

    2) 요소 (element)를 추가할 수 있다
    myNumber.push(96);
    //myNumber =[73, 98, 86, 61, 96]
    //배열 끝에 새로운 element를 넣었음

자세한 설명) 소괄호는 함수 실행할때 봤었는데, push도 함수기 때문에 소괄호를 사용한다. 그래서 push는 method라고 하고, 관련된 명령을 실행하는 것임

  • 3) 요소(element)를 삭제할 수 있다.
    let myNumber = [73, 98, 86, 61]
    myNumber.pop()
    // 배열의 마지막 값이 삭제된다.
    // myNumber = [73, 98, 86]

chapter 1-2 배열의 반복

반복문과 배열을 응용하여 문제를 푸는 법을 배웁니다.

배열과 반복문을 조합하는 경우는 매우 많다.
let myNum = [73, 98, 86, 61];

반복문을 이용해 배열의 element를 한번씩 출력하려면?
문제1) 배열 myNum의 n번째 index를 출력하라.
console.log(myNum[n])
let n = 0;
n < myNum.length;
n++

->

for(let n=0; n < myNum.length; n++){
console.log(myNum[n]);
}

문제2)
myNum의 모든 element를 누적해서 더하기 위해 필요한 조건과, 반복할 구문은?
let myNum = [10, 20, 40, 10];
let sum = 0;
for(let i=0; i<myNum.length; i++){
sum = sum + myNum[i];
}

만약 sum의 값을 0이 아닌 undefined로 설정하면?
// undefined + 10; // NaN;

chapter 1-3 배열 메서드

typeof로는 배열과 객체의 타입이 무엇인지 알 수 없다.
두개다 'object'로 값이 나온다.
예)

let words = ['피', '땀', '눈물']; 
typeof '문자열'
//'string'
typeof 123
//'number'
typeof words
//'object'
let obj = {a : 1}
typeof obj
//'object'
 

그래서 쓸 수 있는 함수는
=> Array.isArray();

Array.isArray('문자열')
//false
Array.isArray(123)
//false
Array.isArray([1, 2, 3])
//true
Array.isArray([])
//true 
//빈 배열도 배열이잖아
let words = [1, 2, 3];
Array.isArray(words)
//true




그 외 꿀팁)

console.table() 로 표로 나타낼 수 있다.

let arr = ['code', 'states']; 
console.table(arr)
(index)  (Value)
0	      'code'
1	     'states'

array.method()를 알아보자

1) push
:배열의 뒤쪽으로 입력값을 넣어준다.

arr.push('pre')
console.table(arr)
0	'code'
1	'states'
2	'pre'

2) pop
: 배열 뒤쪽에 값을 삭제한다.
: 두번 하면 차레로 뒤에서부터 삭제

arr.pop()
//'pre'
arr.pop()
//'states'
console.table(arr)
(index) Value
0	   'code'

3) shift
:앞쪽에 있는 element를 삭제한다.

arr = ['code', 'states']
arr.shift()

arr = ['states']

4) unshift
:element를 배열 앞에 추가한다.

arr = ['states']
arr.unshift('앞에추가')

arr = ['앞에추가', 'states']

자바스크립트의 특정 값이 배열에 포함되어 있는지 확인할 수 있는 indexOf, includes에 대해 배워보자~~

1) indexOf()

  • 특정값이 갖는 배열 인덱스를 말해준다.
  • 특정값이 배열에 없다면, -1을 출력한다.
let words = ['abc', 'deg', 'hh']

words.indexOf('hh')
//2
words.indexOf('있니')
//-1

추가 설명) indexOf()를 통해 그 배열안에 특정값이 있는지 확인하려면 !== -1을 활용한다.

words.indexOf('abc') !== -1
//true
// 특정값이 배열에 있다면 인덱스 값은 -1이 아닌게 맞다. true; 
words.indexOf('없는단어') !== -1
//false 
// 특정값이 배열에 없다면 인덱스 값은 -1이 아닌게 아니다. false

2) 매번 위처럼 써주기 싫다면,함수를 만들어서 활용할 수도 있다. hasElement라는 utility 함수를 만들었다.

function hasElement(arr, element){
    return  arr.indexOf(element) !== -1
}
hasElement(words, 'abc')
//true
hasElement(words, '없는단어')
//false
hasElement(words, abc)
//Uncaught ReferenceError: abc is not defined at <anonymous>:1:19

3) 사실 기본적으로 내장된 method가 있다.
: includes()

words.includes('abc')
//true
words.includes('없는단어')
//false
words.includes(abc)
//Uncaught ReferenceError: abc is not defined
   at <anonymous>:1:16

주의)
그런데 includes는 브라우저 호환성에서 단점을 가지고 있다.
internet explorer에서 includes가 작동하지 않는다,,
indexOf는 모든 브라우저에서 지원하고 있다.

split(), join(), slice(), splice()

profile
팀에 기여하고, 개발자 생태계에 기여하는 엔지니어로

0개의 댓글