2017-10-11 66 views
16

我試圖使Node.js的模塊中使用箭頭函數內isNaN全局函數,但我發現這個錯誤的:ESLint意外請使用isNaN

[eslint] Unexpected use of 'isNaN'. (no-restricted-globals)

這是我的代碼:

const isNumber = value => !isNaN(parseFloat(value)); 

module.exports = { 
    isNumber, 
}; 

有什麼想法我做錯了什麼? PS:我正在使用AirBnB風格指南。

回答

32

作爲documentation suggests,請使用Number.isNaN

const isNumber = value => !Number.isNaN(parseFloat(value)); 

報價Airbnb的文檔:

Why? The global isNaN coerces non-numbers to numbers, returning true for anything that coerces to NaN. If this behavior is desired, make it explicit.

// bad 
isNaN('1.2'); // false 
isNaN('1.2.3'); // true 

// good 
Number.isNaN('1.2.3'); // false 
Number.isNaN(Number('1.2.3')); // true 
+0

哦,真是個小姐!我在mozilla js文檔中搜索,他們使用全局函數。我不知道Number.isNaN()也存在。謝謝! :) –

+0

我提出了答案,但我是Airbnb投票的理由。 – mwilcox

0

僅供參考,這將不會對IE瀏覽器。 在瀏覽器兼容性上檢查here