2017-02-17 3 views
3

は、パフォーマンスの違いはあります。ジャバスクリプト/ typescriptですオブジェクトはnullチェック

Not (empty string, undefined, null, 0, false) - will all pass the condition 

ここで、最初の条件はnullをチェックするだけです。

if (someObject !== null) { 
    console.log('falsey'); 
} 

someObject = null;  // no message in console 
someObject = '';  // falsey 
someObject = undefined; // falsey 
someObject = 0;   // falsey 
someObject = false;  // falsey 

Falseyチェック

if (!someObject) { 
    console.log('falsey'); 
} 

someObject = null;  // no message in console 
someObject = '';  // no message in console 
someObject = undefined; // no message in console 
someObject = 0;   // no message in console 
someObject = false;  // no message in console 
+0

あなたの質問がパフォーマンスに関するものであれば、それを測定するだけです。 – trincot

+0

@Yousuf「4.条件付き評価」のhttps://github.com/rwaldron/idiomatic.jsを読んでください – wf9a5m75

+0

@ wf9a5m75リンクをありがとう、いいリソースのようです。 – Yousuf

答えて

5

!someObject

VSチェック - 以下の2通りの方法ではnullチェックをしながら
+0

!someObjectはすべてのtruthy値を評価しているので、nullをチェックするだけでは効率的ではないのでしょうか? – Yousuf

+0

それはちょうど簡単なチェックであるので、両方のケースでは無視できるほどの性能である、 –

+0

大丈夫、私はそう思った。私の同僚は効率的ではないと私に言ったので、私は疑問に思いました。 – Yousuf

0

@Sushanth! - あなたは、

100%正しくない '偽' の変数をチェックしますが、実際https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/null

!null // true 
をお読みください

だから、

!null // true 
//then 
null // false 

;)

簡単なテストしてください:

var a_null = null; //false 
var b_null = !null //true 

console.log(typeof(a_null)); //object, 'null' is an object. 
console.log(typeof(b_null)); //boolean, now it is not an object. 

if (a_null) var test_a = 1; // 'a_null' is false, so 'test_a' is 'Undefined'. 
if (!a_null) var test_b = 2; // '!a_null' is true, so 'test_b = 2'. 

if (b_null) var test_c = 3; // 'b_null' is true, so 'test_c = 3'. 
if (!b_null) var test_d = 4; // '!b_null' is false, so 'test_d' is 'Undefined'. 

console.log('TEST_A =',test_a,', TEST_B =',test_b,', TEST_C=',test_c,', TEST_D=',test_d); //TEST_A = Undefined, TEST_B = 2, TEST_C = 3 TEST_D = Undefined 

ベスト願いを。

関連する問題