単一/複数値の配列へのコンバート

var $U = {
 
  /* 
  /* function that always returns an array for the input value
   */
  toArray : function(input) {
    try {
       
      if (typeof input === "undefined" || input === null) {
        //return empty array
        return [];  
      }
       
      if (typeof input === "string") {
        //convert string to array (or empty array)
        return ( input.length > 0 ? [input] : [] );
      }
         
      if (typeof input === "java.util.Vector") {
         
        //Normally we would use toArray here, but this returns an Object array.
        //If you try to use that in a doc.replaceItemValue call, it fails.
        //sample code:
        //var v = getComponent("input1").getValue();    //returns a Vector if the component contains multiple values
        //v = $U.toArray(v)   //returns an array of Objects
        //doc.replaceItemValue("someOtherField", v);    //fails
         
        //the solution I used here is to create a JS array and copy the all the Vector's values
        var a = [];
        var it = input.iterator();
        while (it.hasNext() ) {
          a.push( it.next() );
        }
        return a;
      }
       
      if (typeof input.toArray !== "undefined") {
        return input.toArray();
      }
       
      if ( input.constructor === Array ) {
        //return input if it's already an array
        return input;
      } 
   
      //return input as an array
      return [ input ];
       
    } catch(e) {
      print("$U.toArray: " + e.toString());
    }
  }
}





サーバーサイドJavaScript は戻り値が単一の値か複数値かによってメソッドも戻り値も異なるケースがあります。

たとえば、getComponent("input1").getValue() で input1 に複数値が入っていた場合、 Vector を戻り値として返します。単一値の場合は文字列を返します。このような例は、@DbLookup、@DbColumn、@Trim、@Unique にもみられます。

これをうまく処理するのに、この関数でいつも配列に値を返すようにします。

使い方の例は次のとおりです:

var result = $U.toArray( @dbLookup(@dbName, "view", "key", "field") );
var result = $U.toArray( getComponent("input1").getValue() );

(注意:ここでの $U オブジェクトはutility関数のセットとして使用しています)

JavaScript (Server)
katoman
July 13, 2015 at 10:54 AM
Rating
0





No comments yetLogin first to comment...