JS判断数据是否存在字段,存在提示结果

JavaScript019

JS判断数据是否存在字段,存在提示结果,第1张

const data = {

name: 'a',

addr: 'b',

}

console.log('name' in data) // true

console.log('addr' in data) // true

console.log('hello' in data) // false

const data = {

    name: 'a',

    addr: 'b',

}

console.log('name' in data)   // true

console.log('addr' in data)   // true

console.log('hello' in data)  // false

1、isNaN()

使用js自带全局函数isNaN(), isNaN()返回一个Boolean值,如下 :

var c="hello" //字符串

isNaN(c) //返回一个false

var c=10 //数字

inNaN(c)//返回一个true

如果以上c为一个空串或是一个空格,isNaN将把c当作数字0来处理,所以检查不严谨。

2、正则表达式

function checkNum(input){

var reg=/^[0-9]+.?[0-9]*$/ //判断字符串是否为数字 ,判断正整数用/^[1-9]+[0-9]*]*$/

var num=document.getElementById(input).value

if(!reg.test(num)){

        alert("请输入数字")

    document.getElementById(input).value=""

    return false

    }

}

3、利用typeof的返回值

验证方法:如果返回的值为Number,则为数字;如果返回值为String或其它,则不是数字。如下所示:

var a=123

var b='123abc'

typeof(a) //Number

typeof(b) //String