본문 바로가기
Javascript

JavaScript <문자열 배열 다루기>

by mickey7 2023. 3. 5.
<!DOCTYPE html>
<html >
<head>
    <title>Document</title>
</head>
<body>
    <h2>문자열 배열 다루기</h2>
    <hr>
    
    <script>
        let names = new Array("wonsun","jaemoonlee","kitae","gracehwang");
        for(let index in names){
            document.write(names[index]+"\n");
        } //배열 이름 출력

        let long = names[0];
        for(let i =0; i<names.length; i++){
            if(long.length < names[i].length){
                long = names[i]
            }
        } 
        document.write("<br>" + long)
        //배열에서 가장 긴 이름 출력
        
        let dictionaryFirst;
        for(let i=1; i<names.length; i++){
            dictionaryFirst = names[0];
            if(dictionaryFirst > names[i]){
                dictionaryFirst = names[i];
            }
        }
        document.write("<br>"+dictionaryFirst+"<br>");
        //배열에서 가장 먼저 나오는 이름 출력
        
        
        for(let i=0; i<names.length; i++){
            document.write(names[i] + " ")
        } //배열 증가 순 정렬 전

        names.sort();
        document.write("<br>")
        for(let i=0; i<names.length; i++){
            document.write(names[i] + " ")
        }
         //배열 증가 순 정렬 후
         
        //배열을 증가 순으로 재 정렬하여 출력 --> undefined값 Error names[i+1]값이 배열 범위를 넘어서버림.
    </script>
    
</body>
</html>

출력 화면

  • 배열의 메소드 sort()를 마지막에 활용할 생각이 바로 떠오르지 않아서 반복문 안에서 변수를 한 개 더 만들어서 배열의 순서를 바꾸는 방식을 해봤는데 반복문이 배열 지정된 갯수를 넘어가서 undefined 오류가 발생해버렸다. --> sort()메소드 사용할 때는 알파벳일 때는 큰 고려 안해도 되지만 숫자일 때는 유니코드 순으로 정렬되므로 함수를 지정해줘야 원하는 결과 얻을 수 있음!
  • 매번 출력할 때마다 for문을 반복하니 내용을 추가하려면 추가된 내용이 반복문 만큼 반복되서 복잡해진다. --> 차라리 출력하는 함수를 한 개 만들어 두면 편할 듯 예를 들면 아래와 같이 미리 생각했으면 더 쉽게 작성가능!
function printArray(array) {
	for(let i=0; i<array.length; i++)
		document.write(array[i]+" ");
	document.write("<br>");	
}
  • 시행착오를 거쳐서 한 개씩 배워가는 게 제일 좋아보인다.. 예전에 설명으로 들었을 때는 나도 저렇게 해야지 쉽게 생각했는데 직접 해보니 활용은 커녕 생각도 못하는 경우가 발생했다.