JavaScript是一个字符串

JavaScript是一个字符串,javascript,string,Javascript,String,在考虑向字符串原型添加修剪函数时,我发现JavaScript字符串对我来说有些奇怪 if (typeof console === 'undefined') { var console = { }; console.log = function(msg) { alert(msg) } } function isString(str) { return ((str && typeof str === 'string') ||

在考虑向字符串原型添加修剪函数时,我发现JavaScript字符串对我来说有些奇怪

if (typeof console === 'undefined') {
    var console = { };
    console.log = function(msg) {
        alert(msg)
    }
}


function isString(str) {
    return ((str && typeof str === 'string') || 
        (str && (str.constructor == String && (str.toString() !== 'null' && str.toString() !== 'undefined'))));
}

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
    };
}
function testing (str) {
    if (isString(str)) {
        console.log("Trimmed: " + str.trim() + " Length: " + str.trim().length);
    } else {
        console.log("Type of: " + typeof str);
    }
    return false;
}

function testSuite() {
    testing(undefined);
    testing(null);
    testing("\t\r\n");
    testing("   90909090");
    testing("lkkljlkjlkj     ");
    testing("    12345       ");
    testing("lkjfsdaljkdfsalkjdfs");
    testing(new String(undefined));                //Why does this create a string with value 'undefined'
    testing(new String(null));                     //Why does this create a string with value 'null'
    testing(new String("\t\r\n"));
    testing(new String("   90909090"));
    testing(new String("lkkljlkjlkj     "));
    testing(new String("    12345       "));
    testing(new String("lkjfsdaljkdfsalkjdfs"));
}
现在我知道我们不应该使用新运算符创建字符串,但我不希望有人对未定义或空字符串调用此函数,该字符串是按照以下方式创建的:

    new String ( someUndefinedOrNullVar );
我错过了什么?或者是!=='空“&&!==”undefined'检查是否确实必要(删除该检查,将显示'null'和'undefined')?

我相信new String(null)和new String(undefined)返回的值类型是字符串:'null'和'undefined'

编辑: 实际上,null是一个对象。但我认为我关于未定义的观点是正确的。

来自:

…然后:

15.5.2.1 new String ( [ value ] )
The [[Prototype]] internal property of the newly constructed object is set to the standard built-in String prototype object that is the initial value of String.prototype (15.5.3.1).
The [[Class]] internal property of the newly constructed object is set to "String".
The [[Extensible]] internal property of the newly constructed object is set to true.
The [[PrimitiveValue]] internal property of the newly constructed object is set to ToString(value), or to the empty String if value is not supplied.

因此,既然
ToString(undefined)
给出了
'undefined'
,它就有意义了。

JavaScript中的所有对象都可以转换为字符串值,这正是
新字符串(null)
所做的。
!=='空“&&!==”未定义的“
在这种情况下检查是非常简单的,尽管。。。以下所有结果都将生成一个字符串

'' + null // 'null'
'' + undefined // 'undefined'
[null].join() // 'null'

但是我仍然认为,
trim()
不需要额外的愚蠢证明,见鬼,可能有人实际上有一个字符串
'null'
'undefined'
,如果没有,最好能看到,这样你就可以调试它了。不,拿掉支票

修剪功能似乎过于复杂。我认为只要
str.replace(/^\s+|\s+$/,“”)
就足够了。实际上,您的函数对我的测试套件是有效的。我相当确信上面的版本来自Crockford,因此它经常被添加到我正在处理的代码库中。
'' + null // 'null'
'' + undefined // 'undefined'
[null].join() // 'null'