본문 바로가기
javaScript/JS Tutorial

[javaScript]변수가 배열인지 인식하는 방법

by mooyou 2022. 10. 23.
728x90
300x250
SMALL

 

const fruits = ["Banana", "Orange", "Apple"];
let type = typeof fruits;

 

javaScript의 typeof 연산자로 배열을 확인해 보면 object를 반환한다.

 

해결방법 1:

ECMAScript5(JavaScript2009) 새롭게 정의된 메소드 Array.isArray() 사용

const fruits = ["Banana", "Orange", "Apple"];
document.getElementById("demo").innerHTML = Array.isArray(fruits); //true

배열이 맞다면 true를 반환

 

 

해결방법2:

instanceof 연산자는 주어진 생성자에 의해 객체가 생성되면 true를 반환한다.

var fruits = ["Banana", "Orange", "Apple"];
document.getElementById("demo").innerHTML = fruits instanceof Array; //true

 

 

 

참고 : https://www.w3schools.com/js/js_arrays.asp

728x90
반응형
LIST

댓글