조금 더 java 의 format 과 유사한 형태이다.

String.form = function(str, arr) {
    var i = -1;
    function callback(exp, p0, p1, p2, p3, p4) {  
        if (exp=='%%') return '%';
        if (arr[++i]===undefined) return undefined;
        var exp  = p2 ? parseInt(p2.substr(1)) : undefined;
        var base = p3 ? parseInt(p3.substr(1)) : undefined;
        var val;
        switch (p4) {
            case 's': val = arr[i]; break;
            case 'c': val = arr[i][0]; break;
            case 'f': val = parseFloat(arr[i]).toFixed(exp); break;
            case 'p': val = parseFloat(arr[i]).toPrecision(exp); break;
            case 'e': val = parseFloat(arr[i]).toExponential(exp); break;
            case 'x': val = parseInt(arr[i]).toString(base?base:16); break;
            case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break;
        }
        val = typeof(val)=='object' ? JSON.stringify(val) : val.toString(base);
        var sz = parseInt(p1); /* padding size */
        var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */
        while (val.length<sz) val = p0 !== undefined ? val+ch : ch+val; /* isminus? */
       return val;
    }
    var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd])/g;
    return str.replace(regex, callback);
}

if (!String.prototype.format) {
 String.prototype.format = function() {
  return String.form(this, Array.prototype.slice.call(arguments));
 }
}


alert("<tr><td>%s</td><td>%s</td><td>%5.2f</td></tr>".format( "A" , "B" , 12.534));

javascript 의 function 을 사용하다 보면,  파라미터에 대해서 arguments 배열에 접근하여 사용하는 경우가 있다.

이를 통해 유동적인 파라미터를 제어하거나, 기존에 제공되는 api 를 커스터마이징도 할 수 있게 된다.


예시 1) string fomat <= 클릭

예시 2) setTimeout 커스터마이징 <= 클릭


function argLength(one, two){

    console.log("argLength.length : " + argLength.length);

    console.log("arguments.length : " + arguments.length);

}

argLength(1,2,3,4);


위 예제의 결과는

argLength.length : 2

arguments.length : 4

가 나오게 된다.

argLength 라는 function 은 선언되면서 가지게되는 몇가지 멤버변수가 있는데, 그중에 length 부분에는 선언시 정의된 파라미터의 개수가 바인딩된다. 

function 호출시에 파라미터는 function 에서 선언된 파라미터에 arguments 값이 순서대로 맵핑되고, 파라미터가 더 적은 경우에는 undefined 를 가지게 되며, 선언파라미터 많은 경우에는 arguments 배열을 통해 접근이 가능하게 된다.


* 호출

argLength(1);

* 결과

argLength.length : 2

arguments.length : 1

이와 같이 호출시에는 argLength 의 two 값은 undefined 가 되게 된다.



* 실행 테스트 function

var argLength = function(one,two){

     //... 중략

}

으로 선언된 function 이 있다.

아래에서 파라미터를 변경하여 실행하면(ex> argLength("홍길동","무인도","정류소") ), 

one, two 의 값과 argLength.length , arguments.length 를 확인할 수 있다.


 실행테스트

 결과

  

 



이상~

javascript 에서 java의 stringformat 과 유사하게 사용하고 싶은 경우가 있다.

그렇다면 아래 로직을 추가하면된다.


if (!String.prototype.format) {

          String.prototype.format = function() {
               var args = arguments;
               return this.replace(/{(\d+)}/g, function(match, number) {
                    return typeof args[number] != 'undefined' ? args[number]
                              : match;
               });
          };
     }


{숫자} 를 해당 파라미터를 replace 함

(자바스크립트는 파라미터가 arguments 배열로 전달됨, 다른 포스트의 setTimeout 에 파라미터 넘기는 부분에서도 사용함  -> 해당예제)


사용방법 >

var str = "string replace : {0} , {1} => {1} , {0}".format("a","b") 
str 값은 "string replace : a , b => b , a"  가 된다.



'IT > javascript' 카테고리의 다른 글

String fommat 2  (0) 2015.08.03
javascript 의 arguments  (0) 2014.12.03
yuicommpressor (js /css 압축)  (0) 2014.11.24
setTimeout , setInterval , clearTimeout , clearInterval 사용  (0) 2014.11.22
setTimeout 에 파라미터를 넘기는 법  (0) 2014.11.22

javascript 와 css 파일에 대해서는 많은 압축 프로그램들이 있다.

 

yuicommpressor 는 사용결과 다른 압축프로그램보다 압축률이 좋게 나오지는 않았다.

그렇지만 다른압축프로그램에서 발생한 한글문제가 발생하지 않기 때문에 이 압축프로그램을 사용하였다.

 

홈페이지 : http://yui.2clics.net/

 

Usage: java -jar yuicompressor-x.y.z.jar [options] [input file]

 

Global Options

-h, --help                Displays this information(도움말)

--type <js|css>           Specifies the type of the input file(변경하고자 하는 파일의 타입 js 또는 css)

--charset <charset>       Read the input file using <charset>(사용하는 파일의 charset 지정)

--line-break <column>     Insert a line break after the specified column number(특정 컬럼 번호뒤에 줄바꿈 삽입)

-v, --verbose             Display informational messages and warnings(콘솔정보 표시)

-o <file>                 Place the output into <file>. Defaults to stdout.(압축된 파일의 파일명)

 

JavaScript Options

--nomunge                 Minify only, do not obfuscate (난독을 제외한 압축)

--preserve-semi           Preserve all semicolons (세미콜론 유지)

--disable-optimizations   Disable all micro optimizations

                          (foo['bar] => foo.bar and {'bar':x} => {bar:x} 의 형태로 변환을 사용하지 않음)

           

* disable-optimizations 의 추가 설명

disable-optimizations 을 설정하지 않을 경우 아래와 같은 소스로 두가지 메소드가 호출된다.

if (!disableOptimizations) {

        optimizeObjectMemberAccess(this.tokens);

        optimizeObjLitMemberDecl(this.tokens);

    }

optimizeObjectMemberAccess 메소드의 경우 obj["foo"] 를 obj.foo 로 변환하여 3bytes 를 절약한다. 

[]"" 의 4바이트가 제외되고,  . 의 1바이트가 추가된다.

 

optimizeObjLitMemberDecl 의 경우에는 json 내부의 멤버 선언부의 스트링 선언 'foo' 을 foo 로 변환하여

'' 2바이트를 절약한다.

 

사용법>

java -jar yuicompressor-x.y.z.jar myfile.js -o myfile-min.js --charset utf-8

setTimeout은 특정 시간이후 어떤 기능을 실행 할 때 사용하는 함수이다.

setInterval 과의 차이는 반복을 할 것인가, 한번만 실행할 것인가의 차이이다

두 function 모두 동일하게 호출될 function 과 시간을 입력한다(1000 ms = 1 second)

 

- setTimeout : 주어진 시간이 되면 한번 호출

- setInterval : 인터벌 시간마다 반복 호출

 

 

* setTimeout  

 syntax>

    myTimeout= setTimeout("javascript function",milliseconds);

 ex>

    setTimeout(function(){alert("Hello")}, 3000);


* setInterval 

syntax>

   setInterval(function,milliseconds,lang)

ex>

   setInterval(function(){alert("Hello")}, 3000);

  

이 2가지 function 을 초기화 하기 위해서는 clearTimeout, clearInterval 을 사용하며,

function 실행 후 리턴에 대한 값을 가지고 있어야 한다.

 

* clearTimeout 

 ex>

 var myTimeout = setTimeout(function(){

                             console.log("Hello")

                       }, 3000); 

 function myStopFunction() {

    clearTimeout(myTimeout);

 } 


 clearInterval 


 ex>

 var myTimeout= setInterval(function(){

                             console.log("Hello")

                       }, 3000); 

 

 function myStopFunction() {

    clearInterval(myTimeout);

 }


 

'IT > javascript' 카테고리의 다른 글

String fommat 2  (0) 2015.08.03
javascript 의 arguments  (0) 2014.12.03
javascript 에서 string.format 사용  (0) 2014.11.24
yuicommpressor (js /css 압축)  (0) 2014.11.24
setTimeout 에 파라미터를 넘기는 법  (0) 2014.11.22

setTimeout 에 파라미터를 넘기는 법

1. string로 만들어 호출하는 법
   setTimeout( fn 및 param에 대한 스트링, 딜레이시간)   

* 기본 호출

    setTimeout("updateTimeout('value')", 5000);

 * 반복 호출

   setTimeout("updateTimeout(0)", 5000);

   function updateTimeout(i) {

       if (i == 100) return;

       $("#updateVal").val(i++);

       setTimeout("updateTimeout('"+i+"')"5000);
   }

       
    
 2. 외부에서 파라미터 전달(전역변수 사용과 큰 차이가 없다)

 for (var i = 1; i < 100; i++) {

          (function(i) {
               setTimeout(function() {
                     $("#updateVal").val(i);
                }, i * 5000);
         }(i));
    }

 
3. setTimeout 을 재구현

   기본적으로 setTimeout  의 3번째 파라미터 부터는 setTimeout에서 호출하는 function 의 파라미터로 전달 된다. 단. IE 를 제외한 다른 브라우져에서는 전달이 가능하다.

즉 아래와 같은 형태가 된다.

  setTimeout(fn, delayTime , param1, param2 ...)  

  fn(param1, param2 ...)
  {
     내부 구현
  }


  IE 에서 이기능을 제공하기 위해서는  setTimeout 을 재구현하여 사용할 수가 있다.

  var orgTimeout = setTimeout;

   window.setTimeout = function() {
      var func, delay;
      func= arguments[0];
      delay= arguments[1];

      if (arguments.length > 2) {
         var arg = Array.prototype.slice.call(arguments, 2);
         return orgTimeout (function() {
                    func.apply(null, arg);
                }, delay);
       } else {
               return orgTimeout (func, delay);
      }
    };
   
    setTimeout(updateTimeout, 5000, 0);   // 호출가능 해짐


'IT > javascript' 카테고리의 다른 글

String fommat 2  (0) 2015.08.03
javascript 의 arguments  (0) 2014.12.03
javascript 에서 string.format 사용  (0) 2014.11.24
yuicommpressor (js /css 압축)  (0) 2014.11.24
setTimeout , setInterval , clearTimeout , clearInterval 사용  (0) 2014.11.22

+ Recent posts