翻閱古今
2023-07-20 10:55:17
假設我有一個函數(shù),它接受一個數(shù)字并對其執(zhí)行一些操作,例如乘法。如果將字符串或數(shù)字以外的其他內(nèi)容傳遞給其中,我將如何使用該函數(shù)返回 NaN
3 回答

慕沐林林
TA貢獻2016條經(jīng)驗 獲得超9個贊
您可以使用JavaScript的isNaN()函數(shù)。
if(isNaN(num1)){
//is not a number
}else{
//is a number
}

呼喚遠方
TA貢獻1856條經(jīng)驗 獲得超11個贊
const arr = [0,1,'foo',3,4,'bar123', NaN]
arr.map(i => {
if (Number.isNaN(i)) {
console.log(i, 'Number NaN')
} else if (isNaN(i)) {
console.log(i, 'NaN')
}
})

PIPIONE
TA貢獻1829條經(jīng)驗 獲得超9個贊
您可以使用以下命令檢查傳遞給函數(shù)的變量的類型typeof
:
function doSomething(num) {
? ? if(typeof num != "number") {
? ? ? ? return NaN;
? ? }
??
? ? return num * 5;
}
console.log(doSomething(1));
console.log(doSomething("asdf"));
添加回答
舉報
0/150
提交
取消