使用原型设置替换JavaScript字符串?

时间:2014-06-06 02:03:21

标签: javascript string

String.prototype.swap = function(index1,index2) {
    var temp = this[index1];
    return this.substring(0,index1) + this[index2] + this.substring(index1+1,index2) + temp + this.substring(index2+1);
};

var input = "012345";
input.swap(2,4);
console.log(input); // This will print only "012345";
console.log(input.swap(2,4); // This will print "014325";

我想修改原型交换,以便在不创建任何新字符串的情况下替换字符串。这可能吗?

我试过了:

String.prototype.swap = function(index1,index2) {
    var temp = this[index1];
    this = this.substring(0,index1) + this[index2] + this.substring(index1+1,index2) + temp + this.substring(index2+1);
};

但是这会给出分配错误。

有人可以帮我解决这个问题吗?我是新手使用javaScript .. 提前谢谢。

我发现了Does javascript have a method to replace part of a string without creating a new string?。我还想确认这是否可以使用原型的帮助来完成?

0 个答案:

没有答案