자바스크립트의 모든 함수에는 length 프로퍼티가 있습니다.


함수, arr, obj 등에 대한 length에 대해서 작성하도록 하겠습니다.


1. 함수 (Function)


function fncOneparam(param1){};
function fncTwoparam(param1,param2){}
function fncThreeparam(param1,param2,param3){}

console.log("파라미터 1 : ",fncOneparam.length); //  파라미터 1 :  1
console.log("파라미터 2 : ",fncTwoparam.length); //  파라미터 2 :  2
console.log("파라미터 3 : ",fncThreeparam.length);// 파라미터 3 :  3


인자 체크 


function paramCheck(){

	switch(arguments.length){
        case 0: console.info("0개의 파라미터");
				break;
        case 1: console.info("1개의 파라미터");
				break;
        case 2: console.info("2개의 파라미터");
				break;
        case 3: console.info("3개의 파라미터");
				break;
        default:console.info("4개이상의 파라미터");
				break;
    }

}
paramCheck(); // 0개의 파라미터 
paramCheck(1); // 1개의 파라미터 
paramCheck(1,2); // 2개의 파라미터 
paramCheck(1,2,3); // 3개의 파라미터 
paramCheck(1,2,3,4); // 4개이상의 파라미터
paramCheck(1,2,3,4,5); // 4개 이상의 파라미터 


2. 배열 (arr)


var arr = ["a","b","c","d","e","f","g"];

arr.length // 7 


배열 자체로서는 length 하나로 길이를 체크할수 있습니다.


3. 객체 (Object)


객체는 이야기가 조금 나올수 있습니다. 일단  배열안에 객체를넣은 경우와

단순 객체에 대해서 길이 체크를 하겠습니다.

var arrObj = [
{name:"Kim",age:"15"},
{name:"Mim",age:"25"},
{name:"Sim",age:"35"},
{name:"Pim",age:"45"}
];

arrObj.length // 4

// [ ] 로 묶여있기 때문에 단순 배열로 쳐서 length 출력하여도 정상적으로 4가 나옵니다. 

var onlyObj = {name:"test",age:"14",poisiton:"absolute",job:"front",skill:"html"};


console.error(onlyObj.length); // undefined
console.log(Object.keys(onlyObj).length); //  5

// 단순한 obj 의 경우 length 로는 길이를 가져오지 못합니다. 
// Object.keys(obj).length 를 통하여 key 의 개수를 가져올수 있습니다.  length 와 결과 가 같습니다. 



Posted by 깍돌이

블로그 이미지
QA를 업으로 삼고 있습니다.
깍돌이

태그목록

Yesterday
Today
Total

달력

 « |  » 2025.2
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

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함