使用带有正则表达式的test()的第二次调用函数由于某种原因返回不同的结果。我看不出造成这种差异的原因。我想也许它与对象引用有关,但无法跟踪它。
如果我改变函数使用match()(参见第二个函数matchTrees())。它可以找到对函数的第一次和第二次调用。下面有控制台输出的代码段。
var trees = [
{"regX" : /alder$/gi,"id":"Alder"},
{"regX" : /elm/gi,"id":"Elm"},
{"regX" : /ash/gi,"id":"Ash"}
];
function testTrees(treeArray){
var matchedTrees = [];
var i, j;
for (i = 0; i < treeArray.length; i++) {
for (j = 0; j < trees.length; j++) {
if(trees[j].regX.test(treeArray[i])){
//if(treeArray[i].match(trees[j].regX)){
matchedTrees.push(trees[j]);
break;
}
}
}
return matchedTrees;
}
function matchTrees(treeArray){
var matchedTrees = [];
var i, j;
for (i = 0; i < treeArray.length; i++) {
for (j = 0; j < trees.length; j++) {
//if(trees[j].regX.test(treeArray[i])){
if(treeArray[i].match(trees[j].regX)){
matchedTrees.push(trees[j]);
break;
}
}
}
return matchedTrees;
}
var treeArray = ["Elm", "Ash"];
var firstresult;
var secondresult;
console.log("run twice with test()");
firstresult = testTrees(treeArray);
console.log(JSON.stringify(firstresult));
secondresult = testTrees(treeArray);
console.log(JSON.stringify(secondresult));
console.log("run twice with match()");
firstresult = matchTrees(treeArray);
console.log(JSON.stringify(firstresult));
secondresult = matchTrees(treeArray);
console.log(JSON.stringify(secondresult));
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
</body>
</html>