LoginSignup
1
0

More than 5 years have passed since last update.

Node.jsでの型比較について

Last updated at Posted at 2015-11-01

javascriptでは String Number Boolean の3つのプリミティブなデータ型があると書いてあったが、比較する時にどういう挙動をするのか実際にソースに書いて試してみた

app_1.js
 'use strict';

 var main = function(){
     var type_number = 123;
     var type_boolean = true;
     var type_string = 'abc';
     console.log(typeof(type_number));
     console.log(typeof(type_boolean));
     console.log(typeof(type_string));

     console.log(typeof(type_number)  ==  'number' );    // true
     console.log(typeof(type_number)  ==  'Number' );    // false
     console.log(typeof(type_number)  === 'number' );    // true
     console.log(typeof(type_number)  === 'Number' );    // false
     console.log(typeof(type_number)  === Number   );    // false
     console.log(typeof(type_number)  === number   );    // error
     console.log(typeof(type_boolean) ==  'boolean');    // true
     console.log(typeof(type_boolean) ==  'Boolean');    // false
     console.log(typeof(type_boolean) === 'boolean');    // true
     console.log(typeof(type_boolean) === 'Boolean');    // false
     console.log(typeof(type_boolean) ==  Boolean  );    // false
     console.log(typeof(type_boolean) === boolean  );    // error
     console.log(typeof(type_string)  ==  'string' );    // true
     console.log(typeof(type_string)  ==  'String' );    // false
     console.log(typeof(type_string)  === 'string' );    // true
     console.log(typeof(type_string)  === 'String' );    // false
     console.log(typeof(type_string)  ==  String   );    // false
     console.log(typeof(type_string)  ==  string   );    // error
 };  
 main();

number
boolean
string
true
false
true
false
false
true
false
true
false
false
true
false
true
false
false

typeofしたものは'string'とか'number'とか'boolean'とか、頭が小文字になるようにしないと一致しないらしい。

ついでに変数に入るObjectとArrayとFunctionも試してみた

app_2.js
'use strict';

var main = function(){
    var type_object = {key1 : 123, key2 : true, key3 : 'abc'};
    var type_array = [12, 34];
    var type_function = function(){
        console.log('nice boat');
    };
    console.log(typeof(type_object));
    console.log(typeof(type_array));
    console.log(typeof(type_function));

    console.log(typeof(type_object)   ==  'object'   );    // true
    console.log(typeof(type_array)    ==  'object'   );    // true
    console.log(typeof(type_function) ==  'function' );    // true
};
main();

object
object
function
true
true
true

なるほど、Arrayは'object'と認識されるのかと理解。さらにFunctionは'function'になるらしい。

まぁ型の比較がわかったところでどうしたというわけでもないが・・・

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0