javascript判断字符串是否为空

JavaScript018

javascript判断字符串是否为空,第1张

判断是否为空,可以直接用if进行判断,

但全面考虑,还需要判断是否是字符串。

下面是简单的代码,仅供参考:

<body>

    <input type="text" id="inp" />

</body>

<script>

    var oInp = document.getElementById('inp')

    oInp.onblur = function(){

        if(typeof oInp.value == 'string' && !oInp.value){

            console.log('有值!!!')

        }

    }

</script>

js 判断是否为空的代码如下:

//    var a = ""

//    var a = " "

//    var a = null

//    var a = undefined

//    var a = []

//    var a = {}

//    var a = NaN

if(a === undefined) { // 只能用 === 运算来测试某个值是否是未定义的

console.log("为undefined")

}

if(a == null) { // 等同于 a === undefined || a === null

console.log("为null")

}

// String  

if(a == "" || a == null || a == undefined){ // "",null,undefined

console.log("为空")

}

if(!a){ // "",null,undefined,NaN

console.log("为空")

}

if(!$.trim(a)){ // "",null,undefined

console.log("为空")

}

// Array

if(a.length == 0){ // "",[]

console.log("为空")

}

if(!a.length){ // "",[]

console.log("为空")

}

// Object {}

if($.isEmptyObject(a)){ // 普通对象使用 for...in 判断,有 key 即为 false

console.log("为空")

}

JavaScript程序是由若干语句组成的,语句是编写程序的指令。JavaScript提供了完整的基本编程语句,它们是:

赋值语句、switch选择语句、while循环语句、for循环语句、for each循环语句、do...while循环语句、break循环中止语句、continue循环中断语句、with语句、try…catch语句、if语句(if..else,if…else if…)。

说明:typeof 返回的是字符串,有 8 种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined" 、"bigint"、"symbol"

提示:isNaN() 函数通常用于检测 parseFloat() 和 parseInt() 的结果,以判断它们表示的是否是合法的数字。当然也可以用 isNaN() 函数来检测算数错误,比如用 0 作除数的情况。