当我在Javascript中的.exec()结果上使用.index时,它是如何工作的

How does .index work when I use it on the .exec() result in Javascript?

本文关键字:工作 何工作 index Javascript 中的 exec 结果      更新时间:2023-09-26

我正在开发一个程序,该程序使用javascript从一大堆文本中提取信息,在查看以前同事的类似代码时,我发现当您保存该变量的.exec()和do.index的结果时,它会为您提供数组中该子字符串的索引。

Example:
var str="I found this for you!";
var pattern=/this/igm;
var result=pattern.exec(str);
document.write("'"This'" Index = " +  result.index + ".");
Result:
"This" Index = 8.

当我上网查看时,我发现exec()返回了一个数组,看起来数组没有.index属性。我对.index的所有搜索似乎都出现了index()。

这是怎么回事?为什么这样做?我还想知道是否还有其他与此相关的事情可以做(比如.lastindex)。

这里有一个关于exec功能的好资源。它不仅返回一个具有额外属性(如index)的数组,而且还修改了所使用的regex对象。

试试这个:

var str="I found this for you!";
var pattern=/this/igm;
var result=pattern.exec(str);
for(var i in result){
    console.log("i: " + i);
    console.log("result[" + i + "]: " + result[i]);
}
// i: 0
// result[0]: this
// i: index
// result[index]: 8
// i: input
// result[input]: I found this for you!

indexexec添加到数组中的一个特殊属性。它不一定必须默认存在,而且自己复制这种行为非常容易。

var example = [1, 2, 3];
example.index = 15;