본문 바로가기
프론트엔드/JavaScript

[자바스크립트] Arrays (배열)의 methods

by CODESIGN 2022. 4. 22.

배열 (Arrays)


같은 자료들을 담은 자료구조 중의 하나입니다. 

 

 

선언 (Declaration)

const arr1= new Array(1, 2, 3);
const arr2 = [1, 2, 3];

const users = []; // empty array
const numbers = [1, 2, 3]; // array of numbers
const names = ["Sam", "Tom"]; // array of strings
const values = [10, false, "John"]; // mixed

 

 

배열의 길이 (.length)

[].length; // 0

const names = ["Sam", "Tom"];
names.length; // 2

 

 

 

 

배열에 추가하기 (.push)

const names = ["Sam", "Tom"];
names.push("Wendy"); // returns 3 (새로운 배열의 길이)
console.log(names); // ["Sam", "Tom", "Wendy"];
const 알고 가자!
  • const 변수에 할당된 값은 절대로 바뀌지 않습니다. 하지만 위에서 처럼 .push를 사용해 새로운 정보를 추가하였습니다. 어떻게 가능한 걸까요?
  • const 변수에 Object를 할당하면 Object를 가리키는 값이 할당됩니다. 그리고 이 주소 값이 불변이고, 상수입니다. 그리고 그 Objectdp Key-value 쌍을 추가하거나 변경하는 행위는 가능합니다.

    {} === {}가 거짓을 반환하는 이유입니다.

    이처럼 const가 가능한 이유는 const는 한 번만 할당할 수 있음을 의미하기 때문입니다. 그러나 변수가 변경 불가능하다는 의미는 아닙니다. 그 내용은 변경될 수 있습니다.

 

 

 

배열의 반복문 (for, for of, forEach)

names 배열 선언

const names = ["Sam", "Tom"];

 

 

for

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

 

 

for of

for (let name of names) {
	console.log(name);
}

 

 

forEach

forEach는 콜백 함수를 사용합니다. 콜백 함수의 인자로 (값, 인덱스, 배열)로 정의하여 사용합니다.

 

names.forEach(function(name, index, array) {
	console.log(name, index, array);
});

 

 

배열 메서드 (Array method)의 종류

push

배열의 마지막에서부터 값을 추가합니다.

 

const names = ["Sam", "Tom"];

names.push("Tonny", "Alley");
console.log(names);
// ["Sam", "Tom", "Tonny", "Alley"]

 

 

pop

배열의 가장 마지막 값을 삭제합니다.

 

const names = ["Sam", "Tom"];

names.pop();
console.log(names);
// ["Sam"]

 

 

unshift

배열의 가장 앞부분에 값을 추가합니다.

 

const names = ["Sam", "Tom"];

names.unshift("Tonny", "Alley");
console.log(names);
// ["Tonny", "Alley", "Sam", "Tom"]

 

 

shift

배열의 가장 앞의 값을 삭제합니다. 

 

const names = ["Sam", "Tom"];

names.shift();
console.log(names);
// ["Tom"]

 

 

splice

배열에서 원하는 인덱스의 값을 삭제하거나 삭제하고 추가할 수 있습니다.

 

const names = ["Sam", "Tom", "Tonny"];

names.splice(1,1); //인덱스의 1부터 1개 삭제
console.log(names);
// ["Sam", "Tonny"]

 

 

concat

두 개의 배열을 합칩니다. 

 

const names = ["Sam", "Tom"];
const names2 = ["Tonny", "Alley"];

const newNameArray = names.concat(names2); //names와 name2를 연결해줍니다.
console.log(newNameArray);
// ["Sam", "Tom", "Tonny", "Alley"]

 

 

indexOf

배열에서 처음으로 발견된 값의 인덱스를 리턴합니다. 

 

const names = ["Sam", "Tom"];

console.log(names.indexOf("Tom"));
// 1
console.log(names.indexOf("Tonny"); //없는 값을 입력하면 -1을 반환
// -1

 

 

lastIndexOf

배열에서 마지막으로 발견된 값의 인덱스를 리턴합니다.

 

const names = ["Sam", "Tom", "Tom"];


console.log(names.lastIndexOf('Tom'));
// 2

 

 

includes

아이템이 배열에 포함되어있으면 true, 포함이 되어있지 않다면 false를 반환합니다.

 

const names = ["Sam", "Tom"];


console.log(names.include("Sam"));
// true
console.log(names.include("Tonny"));
// false

 

 

 

 

 

Reference

 

Array.prototype.length - JavaScript | MDN

The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

developer.mozilla.org

 

Array.prototype.push() - JavaScript | MDN

The push() method adds one or more elements to the end of an array and returns the new length of the array.

developer.mozilla.org

 

Array.prototype.forEach() - JavaScript | MDN

The forEach() method executes a provided function once for each array element.

developer.mozilla.org

 

 

댓글