帮忙解释下下列代码

var text = "cat,bat,sat,fat";   //数组
  var pattern1 = /.at/;

  var matches = pattern1.exec(text);  //局部变量
  alert(matches.index);     //0
  alert(matches[0]);     //cat
  alert(pattern1.lastIndex);   //0

  matches = pattern1.exec(text);  //全局变量
  alert(matches.index);
  alert(matches[0]);
  alert(pattern1.lastIndex);

  var pattern2 = /.at/g;    //全局变量
  var matches = pattern2.exec(text);
  alert(matches.index);    //0
  alert(matches[0]);     //cat
  alert(pattern2.lastIndex);   //3

  matches = pattern2.exec(text);
  alert(matches.index);         //4
  alert(matches[0]);   //bat
  alert(pattern2.lastIndex);  //7

为什么最后一个alert弹出7呢?pattern1后的全局变量与pattern2后的全局变量不是一个意思吗?

哎呀_哈哈
浏览 1301回答 1
1回答

冠月明金

pattern1不是全局匹配。pattern2是全局匹配pattern2.lastIndex表示下一次匹配开始的下标。执行了两次pattern2.exec(text)下一次开始的下标是7.RegExp.prototype.exec()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript