himorogiの日記

主にプログラミングに関することなど。少々ハード(電子工作)についても。

文字列中の改行の扱い

スクリプトエディタや、AutomatorJavascript から、文字列中に改行を埋め込むには、"\n" ではなくString.fromCharCode(13)を使う必要があるようだ。
つまり、エスケープ文字は無視されるためString.fromCharCode(n)を使う。

スクリプトエディタの場合

app = Application.currentApplication();
app.includeStandardAdditions =true;

function loto(x,y){

	function nGen(){ return ("00" + Math.ceil( Math.random()*y )).substr(-2) }

	for( var list = [ nGen() ]; list.length < x; ){
		if( list.indexOf( a = nGen() )<0 ) list.push( a );
	};
	return list;
}

result  = loto( 5, 31 ).sort().toString() + String.fromCharCode(13);
result += loto( 6, 43 ).sort().toString() + String.fromCharCode(13);
app.displayAlert( result + loto( 7, 37 ).sort().toString() );

結果

01,02,23,28,29
09,18,29,32,38,43
05,13,18,24,28,33,37

Automatorの場合

function run(){

	function loto( x, y ){
		function nGen(){ return ("00" + Math.ceil( Math.random()*y )).substr(-2) }
	
		for( var list =[ nGen() ]; list.length < x; ){
			if( list.indexOf( a = nGen() )) list.push( a ) ;
		};
		return list;
	}
	
	result  = loto( 5,31 ).sort().toString() + String.fromCharCode(13);
	result += loto( 6,43 ).sort().toString() + String.fromCharCode(13);
	return	result + loto( 7,37 ).sort().toString();
}

結果:結果を表示するには、"JavaScript を実行"->"結果を表示"の順にアクションを配置する。

{"01,07,11,19,26
15,24,29,33,37,39
08,09,16,24,27,29,37"}