我遇到了一个需要对 JavaScript 原语有深入了解的人的情况。
问题:我想扩展 String 并添加一个名为“extract”的函数,该函数的功能与“substr”类似,但在返回子字符串的过程中,它也从原始字符串中删除了子字符串。
例如,以下内容不起作用。
if (!String.prototype.extract) {
String.prototype.extract = function (delimiter) {
var copyStr = "";
var i = this.indexOf(delimiter);
if (i >= 0) {
copyStr = this.substr(0, i);
console.log(this); <<-- "String"
//This line doesn't work, don't know what [[PrimitiveValue]] is.
this.[[PrimitiveValue]] = this.replace(copyStr + delimiter,"");
// Nor this line works. Can't modify 'this'
this = this.replace(copyStr + delimiter, "");
}
return copyStr;
}
}
然后我可以这样调用:
var str = "abcdef";
var str2 = str.extract('c');
console.log(str); <<-- this should be 'def'
console.log(str2); <<-- this should be 'abc'
我可以编写一个独立的函数,如下所示,它返回子字符串和修改后的原始字符串,但这不是重点。
function extractSubString(originalStr, delimiter) {
var copyStr = "";
var i = originalStr.indexOf(delimiter);
if (i >= 0) {
copyStr = originalStr.substr(0, i);
originalStr = original.replace(copyStr + delimiter, "");
}
return copyStr;
}
有什么想法吗?
谢谢。
最佳答案
but in the process of returning the sub-string, it also removes the sub-string from the original string.
字符串是不可变的,这意味着它们的值不能以任何方式修改。
关于Javascript:使用 "this"修改字符串的 [[PrimitiveValue]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34093887/