Front end: Determine whether the input data is an integer

ES6 provides Number.isInteger 

Because the obtained value is generally a string, first convert it to parseInt(), and then judge

PS: Because parseInt() is a combination of numbers and non-numbers, if it starts with a letter, it directly returns NaN, because the number part is not intercepted, and the integer cannot be obtained, NaN will be returned. If it starts with a number, intercept the numeric part, stop intercepting when encountering a non-digit or decimal point, and return the result. So console.log("Whether the modified data is an integer ==>", Number.isInteger(parseInt(value))) is defective. (Thanks to the code friend for suggesting the defect♪(・ω・)ノ)

Fix: Before and after using parseInt, judge whether the two strings have the same length.

 

parseInt('a123');//----------返回NaN
parseInt('1a23’);// ---------返回1
parseInt('12a.3');// ---------返回12
parseInt('123.a1');//----------返回123
parseInt('0a11');//-----------返回0
value = "5lkk"
value2 = parseInt(value)
console.log("value=",value) 
console.log("value.length=",value.length ) 
console.log("value2=",value2 ) 
console.log("String(value2).length=",String(value2).length) 
if(value.length == String(value2).length && Number.isInteger(value2)){
console.log("整数") 
}else console.log("bushi整数") 

// console.log("修改后的数据是否为整数==>",Number.isInteger(parseInt(value)))
//PS:因parseInt()若是数字与非数字组合,如果是字母打头,直接返回NaN,因为没有截取到数字部分,取不到
//整数,将返回NaN。如果是数字打头,截取数字部分,遇到非数字或者小数点停止截取,返回结果。所以console.log("修改后的数据是否为整数==>",Number.isInteger(parseInt(value))) 有缺陷。
Number.isInteger(10) // true
Number.isInteger(3.3) // false
Number.isInteger('') // false
Number.isInteger('3') // false
Number.isInteger(true) // false
Number.isInteger([]) // false

 

 

Guess you like

Origin blog.csdn.net/weixin_38676276/article/details/107473436