我正在用 JavaScript 编写一段代码,它应该替换 JSON obj 中多个字符串中出现的所有字符。
并非所有的字符串都包含特定的字符,我们正在谈论很多字符串。所以我的问题是:在谈论效率时,最好是进行替换还是在字符串中搜索字符,并且只有在找到时才进行替换?
换句话说:
var obj = ["str","str2","tr3","str","tr2","str3","str","s22tr2","str3","st","rtr2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3","str","str2","str3"];
选项1:
for(var i=0;i<obj.length;i++){
if(obj[i].indexOf("s")!=-1){
document.write(obj[i].replace(/s/gi,"*"));
}
}
选项2:
for(var i=0;i<obj.length;i++){
document.write(obj[i].replace(/s/gi,"*"));
}
想法?
谢谢。