JavaScript

드림코딩 : JS - 8. array

식초 2020. 10. 19. 11:59
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
'use strict';
 
//Array
 
//1. Declaration (선언)
const arr1 = new Array();
const arr2 = [1,2];
 
 
 
//2. Index position (인덱스 위치)
const fruits = ['apple','banana'];
console.log(fruits);  //["apple","banana"]출력
console.log(fruits.length);
console.log(fruits[0]);  //apple 출력
console.log(fruits[fruits.length - 1]);  //banana 출력, 마지막 인덱스 출력
 
 
 
console.clear();
//3. Looping over an array
//print all fruits
//a. for
for (let i=0; i<fruits.length; i++){
    console.log(fruits[i]);
}
 
//b. for of
for (let fruit of fruits) {
    console.log(fruit);
}
 
//c. forEach
fruits.forEach((fruit, index) => console.log(fruit, index));  //anonymous 함수는 arrow합수(=>)로 만들 수 있다
// (fruit, index, array) 3가지 모두 출력 가능, 1가지만도 출력 가능
//forEach는 배열 안에 들어있는 value들마다 내가 전달한 함수들 출력한다
 
 
 
//4. Addition, deletion, copy (추가, 삭제, 복사)
 
//push: 맨 끝에 item 추가
fruits.push('pear','peach');
console.log(fruits);  //["apple","banana","pear","peach"]
 
//pop: 맨 끝에서 item 지우기
fruits.pop();
fruits.pop();
console.log(fruits);  //["apple","banana"]
 
//unshift: 맨 앞에 item 추가
fruits.unshift('pear','peach');
console.log(fruits);  //["pear","peach","apple","banana"]
 
//shift: 맨 앞에서 item 지우기
fruits.shift();
fruits.shift();
console.log(fruits);  //["apple","banana"]
 
//note!! shift, unshift는 pop, push보다 훨씬 느리다
//당겨오다..shift는 배열을 하나하나 옮겨야하므로 느리다!
 
//splice: 지정된 위치에서 item 지우기
fruits.push('pear','peach','lemon');
console.log(fruits);  //["apple","banana","pear","peach","lemon"] 
//fruits.splice(1);  //["apple"],지정한 인덱스부터 모든 인덱스를 지워버린다
fruits.splice(11);  //1부터 1개만 지울거다
console.log(fruits); //["apple","pear","peach","lemon"]
fruits.splice(1,1,'apple','watermelon');  //지운 자리에 새로운 문자열 넣어라
console.log(fruits);  //["apple","apple","watermelon","peach","lemon"]
 
//두 배열을 합친다
const fruits2 = ['pear','kiwi']
const newFruits = fruits.concat(fruits2);
console.log(newFruits);  //["apple","apple","watermelon","peach","lemon","pear","kiwi"]
 
 
 
//5. Searching (검사)
 
//indesOf: 몇번째에 있는지 찾는다
console.clear();
console.log(fruits);
console.log(fruits.indexOf('apple'));  //0번째
console.log(fruits.indexOf('watermelon'));  //2번째
 
//includes: 배열 안에 있는지 확인한다
console.log(fruits.includes('watermelon'));  //true, 들어있다
console.log(fruits.includes('coconat'));  //false, 없다
console.log(fruits.indexOf('coconat'));  //-1, 배열안에 없다
 
//lastIndexOf
console.clear();
fruits.push('apple');
console.log(fruits);
console.log(fruits.indexOf('apple')); //0, 맨 처음 apple 인덱스 출력
console.log(fruits.lastIndexOf('apple')); //5, 맨 마지막 apple 인덱스 출력
 
 
cs

 

forEach