2017-01-19 46 views
0

測試模塊上運行lint時指出的錯誤:ES6的JavaScript恆返回錯誤

module.exports = (x) => { 
    if (x % 2 === 0) { 
    return 'even'; 
    } else if (x % 2 === 1) { 
    return 'odd'; 
    } else if (x > 100) { 
    return 'big'; 
    } else if (x < 0) { 
    return 'negative'; 
    } 
}; 

運行ESLint:

> yarn lint 
../server/modules/my-awesome-module.js (1/0) 
✖ 3:22 Expected to return a value at the end of this function consistent-return 
✖ 1 error (7:35:56 PM) 
error Command failed with exit code 1. 

什麼是在這種情況下,正確的ES6編碼? 感謝您的反饋

+2

如果不是的情況下'x%2 === 0','x%2 === 1','x> 100'或者'x <0'例如,當x是55.5時 - 應該返回什麼? – Ryan

回答

3

您沒有else的情況。如果您的ifelse if條件都不符合,則沒有返回值。

您可以輕鬆地添加一個默認的else塊,或者只是在函數結尾添加一個簡單的返回值。

+0

謝謝我將添加一個簡單的返回'未定義';在結束括號之前...... – erwin

0

問題是,基於某些代碼路徑(任何if/else子句),函數可能會返回一個值。但是,如果沒有任何情況匹配(例如,x = 50.5),則不返回任何內容。爲了一致性的目的,應該由函數返回一些東西。

一個例子的解決辦法是:

module.exports = (x) => { 
    if (x % 2 === 0) { 
    return 'even'; 
    } else if (x % 2 === 1) { 
    return 'odd'; 
    } else if (x > 100) { 
    return 'big'; 
    } else if (x < 0) { 
    return 'negative'; 
    } 

    return 'none' 
}; 
+0

Justin的回答..這就是我在我的評論中站在 – erwin

0

可以考慮改變代碼段爲

module.exports = (x) => { 
 
    var result = ""; 
 
    if (x % 2 === 0) { 
 
    result = "even"; 
 
    } else if (x % 2 === 1) { 
 
    result = "odd"; 
 
    } else if (x > 100) { 
 
    result = "big"; 
 
    } else if (x < 0) { 
 
    result = "negative"; 
 
    } 
 
    return result; 
 
};

希望它可以幫助

+0

謝謝......實際上我的代碼段被寫入失敗......然後更改if子句的順序以正確處理結果。 .. 謝謝 – erwin