2017-02-17 85 views
3

是否有性能上的差異,而在下面2種方式做null檢查 -的JavaScript /打字稿對象空檢查

if (!someObject) { 
    // dosomething 
} 

VS

if (someObject != null) { 
    // dosomething 
} 
+0

如果你的問題是關於表現,你爲什麼不直接衡量呢? – trincot

+0

@Yousuf在「4.條件評估」中閱讀https://github.com/rwaldron/idiomatic.js – wf9a5m75

+0

@ wf9a5m75感謝您的鏈接,看起來像一個很好的資源。 – Yousuf

回答

5

!someObject檢查所有falsy值。

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

由於!someObject正在評估所有真值,這是否意味着當我僅需要檢查空值時它不是那麼高效? – 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 

最良好的祝願。