JavaScriptはおもしろい

JavaScriptを勉強していますが、おもしろいですね。奇々怪々というところでしょうか。

[sourcecode language="JavaScript"]

var num = "124" - 12; document.writeln("&quot;124&quot; - 12; : " + num + "<br>");

num = "124" / 12; document.writeln("&quot;124&quot; / 12 : " + num + "<br>");

num = "12" * 12; document.writeln("&quot;12&quot; * 12 : " + num + "<br>");

// これは特に注意が必要。数値が文字列として結合される。 num = "12" + 12; document.writeln("&quot;12&quot; + 12 : " + num + "<br>");

-- 実行結果 "124" - 12; : 112 "124" / 12 : 10.333333333333334 "12" * 12 : 144 "12" + 12 : 1212

[/sourcecode]

文字列と数値の演算を行う場合、暗黙的に文字列が数値に変換されるのは便利ですが、一番下の”+”演算のようなケースは文字列と文字列の結合として表現されるというのは注意が必要ですね。

論理値の変換はほかの言語と似ているように思います。ただ、文字列として "false" をセットした場合は論理値型が true となるので注意が必要です。

[sourcecode language="JavaScript"]

var bool_val = Boolean(1); document.writeln("Boolean(1) : " + bool_val + "<br>");

bool_val = Boolean(true); document.writeln("Boolean(true) : " + bool_val + "<br>");

bool_val = Boolean("true"); document.writeln("Boolean(&quot;true&quot;) : " + bool_val + "<br>");

bool_val = Boolean(!null); document.writeln("Boolean(!null) : " + bool_val + "<br>");

bool_val = Boolean(0); document.writeln("Boolean(0) : " + bool_val + "<br>");

bool_val = Boolean(false); document.writeln("Boolean(false) : " + bool_val + "<br>");

// これは注意が必要。文字列としてfalseをセットした場合、インスタンスが!nullのためtrueとなる。 bool_val = Boolean("false"); document.writeln("Boolean(&quot;false&quot;) : " + bool_val + "<br>");

bool_val = Boolean(null); document.writeln("Boolean(null) : " + bool_val + "<br>");

bool_val = Boolean(NaN); document.writeln(" Boolean(NaN) : " + bool_val + "<br>");

-- 実行結果 Boolean(1) : true Boolean(true) : true Boolean("true") : true Boolean(!null) : true Boolean(0) : false Boolean(false) : false

文字列としてfalseをセットした場合、インスタンスが!nullのためtrueとなる Boolean("false") : true Boolean(null) : false Boolean(NaN) : false

[/sourcecode]

型が明確でない言語は、この辺の仕様を抑えないと不可解な挙動に悩まされることをこれまで経験してきましたので、しばらくイントロダクションとして型について理解を深めていこうと思います。