본문 바로가기

Study

[javascript] 배열 관련 함수

1. push(값1, 값2, ...)

- 배열의 마지막에 새로운 요소 추가

- return 값으로 추가된 요소를 포함한 배열의 길이를 돌려줌

1
2
3
4
5
const chores = ['wash dishes''do laundry''take out trash'];
chores.push('arrange towel''open the window');

console.log(chores);    //[ 'wash dishes', 'do laundry', 'take out trash', 'arrange towel', 'open the window' ]
cs

 

2. pop()

- 배열의 마지막 요소 제거

- return 값으로 제거된 요소의 값을 돌려줌

1
2
3
4
5
const chores = ['wash dishes''do laundry''take out trash''cook dinner''mop floor'];
 
let removed = chores.pop();
console.log(chores);        // [ 'wash dishes', 'do laundry', 'take out trash', 'cook dinner' ]
console.log(removed);        // mop floor
cs

 

3. shift()

- 배열의 첫번째 요소 제거

- return 값으로 제거된 요소의 값을 돌려줌

1
2
3
4
5
6
const groceryList = ['orange juice''bananas''coffee beans''brown rice''pasta''coconut oil''plantains'];
 
let shiftValue = groceryList.shift();
 
console.log(groceryList);    // [ 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains' ]
console.log(shiftValue);    // orange juice
cs

 

4. unshift(값1, 값2, ...)

- 배열 맨 처음에 요소 추가

- return 값으로 추가된 요소를 포함한 배열의 길이를 돌려줌

1
2
3
4
5
6
const groceryList = ['orange juice''bananas''coffee beans''brown rice''pasta''coconut oil''plantains'];
 
let unShiftValue = groceryList.unshift('popcorn');
 
console.log(groceryList);    // [ 'popcorn', 'orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains' ]
console.log(unShiftValue);    // 8
cs

 

5. slice(시작인덱스, (끝인덱스))

- 시작인덱스(포함)부터 끝인덱스(미포함)까지의 요소를 return

- 원래 배열은 수정되지 않음

- 끝인덱스를 포함하지 않거나, 끝인덱스가 범위를 초과할 경우 시작인덱스부터 끝까지의 요소를 return

1
2
3
4
const groceryList = ['orange juice''bananas''coffee beans''brown rice''pasta''coconut oil''plantains'];
 
console.log(groceryList.slice(1,4));    // [ 'bananas', 'coffee beans', 'brown rice' ]
console.log(groceryList.slice(3));        // [ 'brown rice', 'pasta', 'coconut oil', 'plantains' ]
cs

 

6. indexOf(값)

- 배열 내에 값이 있는 인덱스를 return

1
2
3
4
const groceryList = ['orange juice''bananas''coffee beans''brown rice''pasta''coconut oil''plantains'];
 
const pastaIndex = groceryList.indexOf('pasta');
console.log(pastaIndex);    // 4
cs

 

'Study' 카테고리의 다른 글

DKIM, DMARC  (0) 2020.05.19
[javascript] iterator 관련 함수  (0) 2020.05.15
[javascript] 변수선언 방식(var, let, const)  (0) 2020.05.14
[javascript] 함수(function) 선언 방법  (0) 2020.05.13
FileZilla Server 설치 및 설정  (0) 2018.01.15