JavaScript是一个字符串吗?

3

在考虑将修剪功能添加到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 操作符创建字符串,但如果有人更像是这样创建了一个未定义或空字符串,我会很讨厌这种情况发生:
    new String ( someUndefinedOrNullVar );

我错过了什么?或者说 !== 'null' && !== 'undefined' 检查是否真的必要(去掉这个检查,将显示“null”和“undefined”)?


那个修剪函数看起来过于复杂了。我认为只需要 str.replace(/^\s+|\s+$/, "") 就足够了。 - Anurag
你的函数实际上已经通过了我设置的测试套件。我相当有信心,上面的版本来自Crockford,因此经常被添加到我正在处理的代码库中。 - Scott
3个回答

4

根据ECMA标准

9.8 ToString
The abstract operation ToString converts its argument to a value of type String according to Table 13 
[ the table shows undefined converts to "undefined" and null to "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',所以这是有意义的。


0
JavaScript 中的所有对象都可以转换为字符串值,这正是 new String(null) 所做的。在这种情况下,!== 'null' && !== 'undefined' 的检查是极其严谨的,尽管...以下所有结果都是字符串。
'' + null // 'null'
'' + undefined // 'undefined'
[null].join() // 'null'

但是在我看来,trim()的额外防错是不必要的。说不定有人实际上有一个字符串'null''undefined',如果没有的话,为了调试也很好看到。不,把检查去掉!


0

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

编辑: 实际上,null 是一个对象。但我认为 undefined 是正确的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接