次のように変数を定義する。
var test1 = 10
var test2 = Number ( 10 ) ;
var test3 = new Number ( 10 ) ;
var test4 = String ( "10" ) ;
var test5 = new String ( "10" ) ;
この場合、実行結果がtrueになるものはどれか。(全て選択)
正解!おめでとう!
解説
JavaScriptの変数は、下の型があるよ。
型 | 詳細 | |
---|---|---|
プリミティブ型 | 数値型 | 数値(例:10) |
文字列型 | 文字(例:"10"、"テスト"、"test") | |
論理型 | 真偽値(例:true、false) | |
未定義型 | 未定義の値 | |
Null値型 | 存在しない値 | |
オブジェクト型 | オブジェクト型 | オブジェクト |
参照型 | 参照 | |
List型 | 配列 |
また、比較演算子は右辺と左辺を比べて、正しいか間違っているかを返してくれる。
比較演算子には下のようなものがあるよ。
比較演算子 | 詳細 |
---|---|
< | 未満 |
> | より大きい |
<= | 以下 |
>= | 以上 |
== | 等しい |
=== | 等しい(かつ型も等しい) |
!= | 等しくない |
!== | 等しくない(または型が等しくない) |
== は、型まで見ないけれど、 === は型まで見て比較する。
それぞれ比較すると、次のような結果になるよ。
左辺 | 比較演算子 | 右辺 | 結果 |
---|---|---|---|
文字列(プリミティブ型) | == | 文字列(プリミティブ型) | true |
文字列(プリミティブ型) | === | 文字列(プリミティブ型) | true |
文字列(プリミティブ型) | == | 文字列(オブジェクト型) | true |
文字列(プリミティブ型) | === | 文字列(オブジェクト型) | false |
文字列(プリミティブ型) | == | 数値(プリミティブ型) | true |
文字列(プリミティブ型) | === | 数値(プリミティブ型) | false |
文字列(プリミティブ型) | == | 数値(オブジェクト型) | true |
文字列(プリミティブ型) | === | 数値(オブジェクト型) | false |
数値(プリミティブ型) | == | 数値(プリミティブ型) | true |
数値(プリミティブ型) | === | 数値(プリミティブ型) | true |
数値(プリミティブ型) | == | 数値(オブジェクト型) | true |
数値(プリミティブ型) | === | 数値(オブジェクト型) | false |
Numberオブジェクトは、数値を返すもの。Numberオブジェクトにnewを付けると、オブジェクト型の数値を返してくれるよ。
一方、Stringオブジェクトは、文字列を返すもの。Stringオブジェクトにnewを付けると、オブジェクト型の文字列を返してくれるよ。
問題と同じように作った、サンプルコードはこちら。
var test1 = 10
var test2 = Number(10);
var test3 = new Number(10);
var test4 = String("10");
var test5 = new String("10");
console.log( typeof test1 );
console.log( typeof test2 );
console.log( typeof test3 );
console.log( typeof test4 );
console.log( typeof test5 );
console.log( test1 == test2 );
console.log( test1 == test3 );
console.log( test1 == test4 );
console.log( test1 == test5 );
console.log( test2 == test3 );
console.log( test2 == test4 );
console.log( test2 == test5 );
console.log( test3 == test4 );
console.log( test3 == test5 );
console.log( test4 == test5 );
console.log( test1 === test2 );
console.log( test1 === test3 );
console.log( test1 === test4 );
console.log( test1 === test5 );
console.log( test2 === test3 );
console.log( test2 === test4 );
console.log( test2 === test5 );
console.log( test3 === test4 );
console.log( test3 === test5 );
console.log( test4 === test5 );
F12キーを押して、コンソールでサンプルコードを実行すると、consoleオブジェクトのlogメソッドで変数の型と比較結果が返ってくるよ。
typeofは型を返すもの。
test1はnumberなので数値(プリミティブ型)、test2はnumberなので数値(プリミティブ型)、test3はobjectなので数値(オブジェクト型)、test4はstringなので文字列(プリミティブ型)、test5はobjectなので文字列(オブジェクト型)ということが分かる。
そのため、trueになる下の3つが正解。
おしい…もう一度…!
Comment