JS 判断空字符串

JS 判断空字符串

在很多情景下,需要对字符串进行判空的操作,例如表单提交或获取后端数值。

1、typeof 判断 undefiend

typeof是一个运算符,有2种使用方式:typeof(表达式)和typeof 变量名,第一种是对表达式做运算,第二种是对变量做运算。

typeof的返回值

  1. 'undefined' --未定义的变量或值
  2. 'boolean' --布尔类型的变量或值
  3. 'string' --字符串类型的变量或值
  4. 'number' --数字类型的变量或值
  5. 'object' --对象类型的变量或值,或者null(这个是js历史遗留问题,将null作为object类型处理)
  6. 'function' --函数类型的变量或值
var content;
if(typeof content === "undefined")  //true

变量定义后为赋值即为 undefined

2、判断null

var content = null;
if(typeof content === null)  //true

3、trim()判断空格

trim() 方法用于删除字符串的头尾空白符,空白符包括:空格、制表符 tab、换行符等其他空白符等。

var content = "             ";           //一列空格
if(typeof content.trim() === "")             //true

4、总的写法

综上,上面的判断顺序不能变换,写法如下:

if(typeof content === "undefined" || content === null || content.trim() === "") {
    this.$message({
        showClose: true,
        message: '空字符串',
        type: 'error'
    });
}

参考文章:https://www.jianshu.com/p/8107d25f54ac

自我控制是最强者的本能-萧伯纳
原文地址:https://www.cnblogs.com/CF1314/p/14025031.html