gpt4 book ai didi

javascript - replaceAll 函数 : Script too long to execute

转载 作者:行者123 更新时间:2023-11-30 12:43:23 27 4
gpt4 key购买 nike

这是我的代码:

String.prototype.replaceAll = function(search, replace){
if(!replace){
return this;
}

while(this.indexOf(search) !== false){
this.replace(search, replace);
}

return this;
};

我想它应该可以工作,但它没有。

代码应该像这样工作:

var x="hihi";
x.replaceAll("hi", "i");

最后 x 的值应该是:

ii

最佳答案

我更喜欢这样做。

String.prototype.replaceAll = function (search, replace) {
var str = this;
var pos = str.indexOf(search);
while (pos > -1) {
str = str.replace(search, replace);
pos = str.indexOf(search);
}
return (str);
};

但在您的情况下,您必须将“!== false”替换为“> -1”并从“this.replace(search, replace);”返回您必须放入一个变量,因为“替换”函数不会更改“this”的值,只会返回新的字符串值。

关于javascript - replaceAll 函数 : Script too long to execute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23541413/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com