희락코딩

JavaScript _개념정리/ 배열 본문

프로그래밍/자바스크립트 개념 정리

JavaScript _개념정리/ 배열

Hello JoyCoding 2021. 4. 20. 00:46
728x90
반응형

배열


배열array은 여러 개의 값을 순차적으로 나열한 자료구조다.

배열이 가지고 있는 값을 요소(element)라고 부른다. 자바스크립트의 모든 값은 배열의 요소가 될 수 있다. 즉, 원시값은 물론 객체, 함수, 배열 등 자바스크립트에서 값으로 인정하는 모든 것은 배열의 요소가 될 수 있다.

 

배열의 요소는 배열에서 자신의 위치를 나타내는 0 이상인 정수인 인덱스(index)를 갖는다. 인덱스는 배열의 요소에 접근할 때 사용한다. 대부분의 프로그래밍 언어에서 인덱스는 0 부터 시작한다.

 

요소에 접근할 때는 대괄호[] 표기법을 사용한다. 대괄호 내에는 접근하고 싶은 요소의 인덱스를 지정한다.배열의 요소의 개수, 즉 배열의 길이를 나타내는 length 프로퍼티를 갖는다.

 

 

▶ 배열에서 특정 인덱스의 요소를 조회 및 변경하는 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//1. 배열의 구성
 
const arr = ['teemo''baba''jax'];  
//  인덱스      0        1       2   
//arr는 3개의 요소 teemo, baba, jax 로 구성되어 있다.
 
//2. 괄호 내에서 접근하는 방법
 
arr[0// 'teemo'
arr[1// 'baba'
arr[2// 'jax'
 
 
//3. 배열의 길이를 확인하는 방법
 
arr.length // 3
 
 
//4. 배열 안에 마지막 요소 접근
 
        ['teemo''baba''jax']; 
배열길이     1       2       3
인덱스       0       1       2      
 
요소의 마지막 인덱스가2 임으로 배열의길이 마지막인3에서 1을 빼면 배열 요소의 마지막 값을 조회할수있습니다.
배열 요소의 마지막 값 -> arr.length - 1
 
 
//5. 배열안에 있는 요소 변경
 
//인덱스를 이용해서 변경할수있습니다.
const arr = ['teemo''baba''jax']; 
 
arr[0= 'code'
 
console.log(arr);  // ['code', 'baba', 'jax']; 
 
//delete를 사용해서 변경
 
const arr = ['teemo''baba''jax']; 
 
delete arr[0//  [empty, 'baba', 'jax'];
// 주의 이때 배열안의 요소는 변경 되었지만 배열의 길이는 변화가 없습니다.
 
cs

 

 

▶ 배열 내에 배열이 있는 이중 배열의 요소의 조회 및 변경 하는 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
이중배열 조회 및 변경
 
let number = [[12,22], [41,23],[42,56]]
 
//number의 2번째 인덱스 값은 ?
 
number[2]  // [42, 56]
 
//number의 1번째 인덱스의 1번째 인덱스 값은 ?
 
number[1][1// 23
 
 
  let number =   [[12,22], [41,23],[42,56]]
//첫번째배열index     0        1       2
//두번째배열index   0   1    0   1   0   1
//꿀팁을 알려주자면 콘솔창에 console.table(number) 치면 number의 배열길이와 인덱스를 직관적으로 확인할수 있습니다.
cs

 

 

▶ 배열의 반복문 활용 방법

배열은 인덱스와 length 프로퍼티를 갖기 때문에 for 문을 통해 순차적으로 요소에 접근할 수 있습니다. 배열의 반복문도 기존 반복문의 구조와 매우 비슷합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//배열의 반복문 구조
 
const arr= [1,2,3]
 
for(let i = 0; i < arr.length; i++){  // 배열의 반복문에서 arr.length를 유심히 보자!!
      console.log(arr[i]);    //1, 2, 3
}
 
 
//ex) 다음 배열 안에있는 인덱스 3전까지의 요소 불러오기
 
const myarr = ['teemo''baba''koko''bug''code']
 
for(let i = 0; i < myarr.length; i++){
   if(i < 3){
console.log(myarr[i]);}
}
 
// teemo, baba, koko
 
 
// ex) 배열 반복문을 활용해서 최대값 구하기
 
arr = [11,4,20,1,6,77,43,54,9]
 
function maxArr(arr){
 let max = arr[0];                       //max 값을 배열의 첫번째 요소로 초기화
for(let i = 0; i < arr.length; i++){     // 배열 반복문
   if(arr[i] > max){                     // arr[i] > max 조건 설정
     max = arr[i];}                      // max = arr[i] 최대값 구하기 실행
    }
  return max;                            // max값 반환하기.
}
 
 
// 풀어서 설명
 
// [11,4,22,1,6,77,43,54,9]
 
 
// arr[0] > arr[0]    11 > 11  조건 성립x 
// arr[1] > arr[0]    4  > 11  조건 성립x 
// arr[2] > arr[0]    20 > 11  조건 성립o  max = arr[i]; 최대값
// arr[3] > arr[0]    1  > 20  조건 성립x 
// arr[4] > arr[0]    6  > 20  조건 성립x 
// arr[5] > arr[0]    77 > 20  조건 성립o  max = arr[i]; 현재 최대값
// arr[6] > arr[0]    43 > 77  조건 성립x 
// arr[7] > arr[0]    54 > 77  조건 성립x 
// arr[8] > arr[0]    9  > 77  조건 성립x 
 
// return max 현재 최대값 출력 77
cs

 

 

▶ 배열인지 아닌지 확인하는 방법

Array.isArray는 배열을 확인해주는 메서드 입니다. 배열이면 true 아니면 false 값을 반환합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
//true
 
Array.isArray([]);
Array.isArray([1,4]);
Array.isArray(new Array());
 
 
// false
 
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(1);
Array.isArray(undefined);
Array.isArray('Array');                             
Array.isArray(true);
Array.isArray(false);
 
cs

 

Array.isArray()


Array.isArray() 메서드는 인자가 Array인지 판별합니다.

또 한 객체가 배열이면 true를 반환하고, 아니면 false를 반환합니다.

 

Array.isArray([1, 2, 3]);     // true    [] 은 배열임으로 true를 반환합니다.
Array.isArray({foo: 123});  // false  {} 객체임으로 false를 반환합니다.   
Array.isArray('foobar');    // false   따옴표 안에 들어간 문자열임으로 false 를 반환합니다.
Array.isArray(undefined); // false   undefined은 정의 되지 않은 값임으로 false를 반환합니다.

 

※ 주의

변수로 담은 배열 또한 true 값으로 반환 합니다.

 

const joyNumber = [1,3,4,5,6,7];  // 변수로 담은 배열

Array.isArray(joyNumber);    // true

참고자료

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

 

Array.isArray() - JavaScript | MDN

Array.isArray() Array.isArray() 메서드는 인자가 Array인지 판별합니다. Array.isArray([1, 2, 3]); // true Array.isArray({foo: 123}); // false Array.isArray('foobar'); // false Array.isArray(undefined); // false 객체가 Array라면 true, 아

developer.mozilla.org

 

▶ 배열에 쓰이는 기본 메서드

배열에 자주 쓰이는 메서드는 배열의 포함, 요소 조회, 추가, 삭제, 복사, 분리가 있습니다.

드림코딩 예제를 통해서 알아 봅시다!

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
Array
 
//1. Declaration ->> 배열 선언
const arr1 = new Array();
const arr2 = [1,2];
 
//2. Index postion ->> 인덱스 위치
const fruits = ['apple''banana''tomato''strawberry'];
console.log(fruits);        // ["apple", "banana", "tomato", "strawberry"]
console.log(fruits[0]);     //   "apple"
console.log(fruits[1]);     //   "banana"
console.log(fruits[2]);     //   "tomato"
console.log(fruits[fruits.length-1]);  // "strawberry"
 
//3. Looping over an  array  ->> 배열의 반복
// print all fruits
// a. for
const fruits = ['apple''banana''tomato''strawberry'];
for(let i=0; i<fruits.length; i++){
console.log(fruits[i]);         
}
// 'apple', 'banana', 'tomato', 'strawberry'
 
 
 
// b. for of   ->> 반복문이랑 같은 개념 
const fruits = ['apple''banana''tomato''strawberry'];
for(let fruit of fruits){
console.log(fruit);
}
 
// c. forEach() ->> 콜백함수
const fruits = ['apple''banana''tomato''strawberry'];
fruits.forEach(function (fruit, index){
console.log(fruit, index);
});
 
const fruits = ['apple''banana''tomato''strawberry'];
fruits.forEach((fruit, index) =>
console.log(fruit, index));
//------------------------------같은 개념 다만 =>이건 고수들만 한다는 화살표 함수
// 출력하면 'apple', 0, 'banana',1, 'tomato',2, 'strawberry' 3 
// 요소와 인덱스값이 같이 나옴
 
여기서부터 우리가 알아야될 중요한 메서드 꼭 이해하고 콘솔창에 치면서 연습하자
//4. Addtion, deletion, copy 
// push: add an item to the end ->> push는 뒤에 요소 추가
const fruits = ['apple''banana''tomato''strawberry'];
fruits.push('peach','kiwi');
console.log(fruits);
// ["apple", "banana", "tomato", "strawberry", "peach", "kiwi"]
 
 
//pop: remove an item from the end ->> pop은 뒤에 요소 제거
const fruits = ['apple''banana''tomato''strawberry'];
fruits.pop();
console.log(fruits);
// ["apple", "banana", "tomato"]
 
 
//unshift : add an item to the benigging ->> unshift는 앞에 요소 추가
const fruits = ['apple''banana''tomato''strawberry'];
fruits.unshift('grape''cherry');
console.log(fruits);
// ["grape", "cherry", "apple", "banana", "tomato", "strawberry"]
 
 
//shift : remove an item from the benigging ->> shift()는 앞에 요소 제거
const fruits = ['apple''banana''tomato''strawberry'];
fruits.shift();
console.log(fruits);
// ["banana", "tomato", "strawberry"]
 
//note!!! shift, unshift are slower than pop, push
//설명 강의 설명 참고!!
 
//여기부분은 전 파트에서 배운 내용 복습해보자!!
//splice: remove an item by index position
const fruits = ['apple''banana''tomato''strawberry'];
fruits.splice(1);
console.log(fruits);
// ["apple"]
 
 
const fruits = ['apple''banana''tomato''strawberry'];
fruits.splice(1,1);
console.log(fruits);
// ["apple", "tomato", "strawberry"]
 
 
const fruits = ['apple''banana''tomato''strawberry'];
fruits.splice(1,1,'melon','lemon');
console.log(fruits);
// ["apple", "melon", "lemon", "tomato", "strawberry"]
 
 
// concat메소드는 확실히 알아두자 배열과 배열을 합칠때 유용한 메서드중 하나다!!
//combine two arrays 
const fruits = ['apple''banana''tomato''strawberry'];
const fruits2 = ['blueberry','mango']
const newFruits = fruits.concat(fruits2);
console.log(newFruits);
// ["apple", "banana", "tomato", "strawberry", "blueberry", "mango"]
 
 
 
//5. Searching
// find the index  ->>  배열요소의 인덱스 값을 찾고 없으면 -1로 출력된다.
const fruits = ['apple''banana''tomato''strawberry'];
console.log(fruits);                     // ["apple", "banana", "tomato", "strawberry"]
console.log(fruits.indexOf('banana'));   //  1
console.log(fruits.indexOf('apple'));    //  0
console.log(fruits.indexOf('lemon'));    // -1
 
// includes    ->> 배열안에 있는 요소가 포함되어 있으면 true 아니면 false로 출력 된다.
const fruits = ['apple''banana''tomato''strawberry'];
console.log(fruits.includes('tomato'));  // true
console.log(fruits.includes('mango'));   // false
 
 
// lastIndexOf  ->> 배열안에 똑같은 요소가 있을때 쓰는 메
const fruits = ['apple''banana''tomato''apple'];
console.log(fruits);                          // ["apple", "banana", "tomato", "apple"]
console.log(fruits.indexOf('apple'));         // 0
console.log(fruits.lastIndexOf('apple'));     // 3
cs

 

참고 사이트

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

 

 

 

 

728x90
반응형
Comments