JS 객체

shinyeongwoon·2022년 10월 25일
0

JS

목록 보기
9/16

객체

여러 개의 자료형을 한 번에 저장하는 자료형

배열,함수, 배열이나 함수가 아닌 객체

배열

const fruits = ['사과','오렌지','배','딸기'];

배열 내부의 값 불러오기

const fruits = ['사과','오렌지','배','딸기'];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[3]);

결과 )
"사과"
"오렌지"
"배"

배열 안에는 다른 배열이나 변수를 넣을 수 있음

const arrayOfArray = [[1,2,3],[4,5]];
arrayOfArray[0];
const a = 10;
const b = 20;
const variableArray = [a,b,30];
variableArray[1];

결과 )
[1,2,3]
20

배열은 내부의 값 중복 가능, 아무 값 없이 만들 수 있음

const e = ['사과',1,undefined,true,'배열', null];
const dupl = ['가','가','가','가'];
const empt = [];

배열 요소 개수 구하기 : 배열 이름 뒤 .length

const e = ['사과',1,undefined,true,'배열', null];
console.log(e.length);

결과 )
6

빈값도 요소 개수 셀 때 포함됨

배열에 요소 추가하기

const target = [1,2,3,4,5];
target[5] = 6;
console.log(target);

결과 )
[1,2,3,4,5,6]

배열 맨 앞에 요소 추가하기 : unshift

const target = [2,3,4,5];
target.unshift(1);
console.log(target);

결과 )
[1,2,3,4,5]

배열 맨 뒤에 요소 추가하기 : push

const target = [1,2,3,4];
target.push(5);
console.log(target);

결과 )
[1,2,3,4,5]

배열의 마지막 요소 제거 : pop채

const target = [1,2,3,4,5];
target.pop();
console.log(target);

결과 )
[1,2,3,4]

배열의 첫번째 요소 제거 : shift

const target = [1,2,3,4,5];
target.shift();
console.log(target);

결과 )
[2,3,4,5]

배열의 중간요소 제거 : splice , slice

const target = [1,2,3,4,5];
target.splice(1,1);
console.log(target);

결과 )
[1,3,4,5]

const target = [1,2,3,4,5];
target.slice(3);
console.log(target);

결과 )
[1,2,3]

배열에서 요소 찾기

includes

const target = [1,2,3,4,5];
const result = target.includes(2);
const result2 = target.includes(6);
console.log(result);
console.log(result2);

결과 )
true
false

indexof
lastIndexOf

const target = [1,2,3,4,2];
const result = target.indexOf(2);
const result2 = target.lastIndexOf(2);
const result3 = target.indexof(6);
console.log(result1);
console.log(result2);
console.log(result3);

결과 )
1
4
-1

배열 순회
while

const target = [1,2,3,4,5];
let i = 0;
while(i < target.length){
	console.log(target[i]);
  	i++;
}

for

const target = [1,2,3,4,5];
for(let i = 0; i < target.length; i++){
	console.log(target[i]);
}

0개의 댓글