3 回答

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊
若要檢查變量(包括字符串)是否為數(shù)字,請(qǐng)檢查它是否不是數(shù)字:
不管變量?jī)?nèi)容是字符串還是數(shù)字,這都是可行的。
isNaN(num) // returns true if the variable does NOT contain a valid number
實(shí)例
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
當(dāng)然,如果你需要的話,你可以否定這一點(diǎn)。例如,要實(shí)現(xiàn)IsNumeric你給的例子:
function isNumeric(num){
return !isNaN(num)
}
若要將包含數(shù)字的字符串轉(zhuǎn)換為數(shù)字,請(qǐng)執(zhí)行以下操作:
只有在字符串有效的情況下才能工作。只包含數(shù)字字符,否則它將返回。NaN.
+num // returns the numeric value of the string, or NaN
// if the string isn't purely numeric characters
實(shí)例
+'12' // 12
+'12.' // 12
+'12..' // Nan
+'.12' // 0.12
+'..12' // Nan
+'foo' // NaN
+'12px' // NaN
松散地將字符串轉(zhuǎn)換為數(shù)字
用于將“12 px”轉(zhuǎn)換為12,例如:
parseInt(num) // extracts a numeric value from the
// start of the string, or NaN.
實(shí)例
parseInt('12') // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last two may be different
parseInt('12a5') // 12 from what you expected to see.
浮子
記住,不像+num, parseInt(顧名思義)將通過(guò)切分小數(shù)點(diǎn)后的所有內(nèi)容將浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù)(如果要使用parseInt() 因?yàn)檫@種行為,你最好還是用另一種方法代替):
+'12.345' // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12
空字符串
空字符串可能有點(diǎn)違背直覺(jué)。+num將空字符串轉(zhuǎn)換為零,并且isNaN()假設(shè)情況相同:
+'' // 0
isNaN('') // false
但parseInt()不同意:
parseInt('') // NaN

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊
var num = "987238";if(num.match(/^-{0,1}\d+$/)){ //valid integer (positive or negative)}else if(num.match(/^\d+\.\d+$/)){ //valid float}else{ //not valid number}

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果您只是想檢查一個(gè)字符串是否是一個(gè)整數(shù)(沒(méi)有小數(shù)位),regex是一個(gè)很好的方法。其他方法,如isNaN對(duì)這么簡(jiǎn)單的事情來(lái)說(shuō)太復(fù)雜了。
function isNumeric(value) {
return /^-{0,1}\d+$/.test(value);
}
console.log(isNumeric('abcd')); // false
console.log(isNumeric('123a')); // false
console.log(isNumeric('1')); // true
console.log(isNumeric('1234567890')); // true
console.log(isNumeric('-23')); // true
console.log(isNumeric(1234)); // true
console.log(isNumeric('123.4')); // false
console.log(isNumeric('')); // false
console.log(isNumeric(undefined)); // false
console.log(isNumeric(null)); // false
只允許陽(yáng)性整數(shù)使用如下:
function isNumeric(value) {
return /^\d+$/.test(value);
}
console.log(isNumeric('123')); // true
console.log(isNumeric('-23')); // false
添加回答
舉報(bào)