我正在开发一个程序,该程序使用 javascript 从大量文本中提取信息,并且在查看类似代码的前同事代码时,我发现当您保存 .exec() 的结果并执行 .该变量的索引它为您提供数组中该子字符串的索引。
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)。
最佳答案
Here is a great resource on what exec
does.它不仅返回一个具有额外属性(如 index
)的数组,而且还修改所使用的正则表达式对象。
试试这个:
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!
关于javascript - 当我在 Javascript 中的 .exec() 结果上使用 .index 时,它是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11460955/