如何安全地确定变量是否是多个字符的字符串

How can I safely decide if a variable is a string of more than one characters?

本文关键字:是否是 变量 字符 字符串 何安全 安全      更新时间:2023-09-26

我正在使用以下Javascript:

 if (typeof content !== 'undefined' && content.length > 0) {
    $state.transitionTo('admin.content', { content: content })
 }

我认为这是安全的使用,但它给了我一个错误说:

TypeError: Cannot read property 'length' of null

我使用以下函数来确定某物是否为数字:

    isNumber: function (num) {
        // Return false if num is null or an empty string
        if (num === null || (typeof num === "string" && num.length === 0)) {
            return false;
        }
        var rtn = !isNaN(num)
        return rtn;
    },

我怎样才能编写一个类似的函数来非常安全地确定长度大于 0 的字符串是什么?

if (typeof num === "string" && num.length > 0)
{
  alert("You've got yourself a string with more than 0 characters");
} 

if (typeof(num) === "string" && num.length > 0) {...}

我想

补充现有的答案。如果字符串对象是通过新的构造函数创建的,则以下代码将返回 false

var stringObj = new String("my string");
typeof stringObj === "string" // this will be false, because the type is object

更好的方法是通过 stringObj 的构造函数属性进行测试

stringObj.constructor === String

如果以以下两种方式创建字符串 Obj 时,则此条件为 true

var stringObj = "my string";
Or    
var stringObj = new String("my string");