JavaScript 是 item 一个字符串

标签 javascript string

在考虑向 String 原型(prototype)添加 trim 函数时,我遇到了一些对 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')?

最佳答案

来自ECMA standard :

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',所以这是有道理的。

关于JavaScript 是 item 一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3630477/

相关文章:

javascript - 处理gmappanel extJS中的点击事件

javascript - Facebook iFrame JavaScript SDK - 不带 OAuth

javascript - 如何使用javascript获取给定开始日期和结束日期之间的所有日期?

c++ - 使用 operator+ 而不会泄漏内存?

javascript - 谷歌地图替代道路以不同颜色显示

javascript - 使用 AJAX 查找元素的文本

c++ - 在默认参数上重载方法

java - Log4j 最大字符串长度或 Java 字符串连接错误?

xml - 如何在多个 xml 文件中搜索 linux 中两个标签之间出现的字符串?

mysql - 为什么MySQL隐式地将没有数据转换为空字符串?