• 手机版

    扫码体验手机版

  • 微信公众号

    扫码关注公众号

国内首家协议开发

软芯音视解码保护平台

在线
客服

发布
需求

在线
聊天

天盟
APP

天盟APP下载

关注
微信

微信扫一扫访问
顶部

帮忙解释下下列代码

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后的全局变量不是一个意思吗?

免责声明:本内容仅代表回答会员见解不代表天盟观点,请谨慎对待。

版权声明:作者保留权利,不代表天盟立场。

使用道具 举报

全部参与1

pattern1不是全局匹配。
pattern2是全局匹配pattern2.lastIndex表示下一次匹配开始的下标。

执行了两次pattern2.exec(text)下一次开始的下标是7.
RegExp.prototype.exec()

使用道具 举报

发新帖

发布任务需求已有1031167位用户正在使用天盟网服务

发布分类: *
任务预算: *
需求内容: *
手机号码: *
任务商家报价为
  • 预算价 :
  • 成交价 :
  • 完工期 :
  • 质保期 :

* 最终任务项目以服务商报价、双方协商为准!