JS实现split

String.prototype.split2 = function (symbol) {
  const reg = new RegExp("(.?)" + symbol, "g");
  const rstArr = [];
  this.replace(reg, function ($0, $1) {
    rstArr.push($1);
  });
  if (this.slice(0) === symbol) {
    rstArr.unshift('');
  }
  if (this.slice(-1) === symbol) {
    rstArr.push('');
  }
  return rstArr;
};
let i = 0;
console.time('1');
while (i++ < 1000) {
  const t = "@1@s@s1@222@[email protected]@12pp@".split2("@");
  const t1 = "1@s@s1@222@[email protected]@12pp@".split2("@");
  const t2 = "1@s@s1@222@[email protected]@12pp".split2("@");
}
console.timeEnd('1');

i = 0;
console.time('2');
while (i++ < 1000) {
  const t = "@1@s@s1@222@[email protected]@12pp@".split("@");
  const t1 = "1@s@s1@222@[email protected]@12pp@".split("@");
  const t2 = "1@s@s1@222@[email protected]@12pp".split("@");
}
console.timeEnd('2');

肯定不如内置的快啦

猜你喜欢

转载自blog.csdn.net/qq_39571197/article/details/83011634