在考虑将修剪功能添加到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