如何在集合中搜索多个短语之间第一次出现的位置?鉴于下面的示例测试代码,第一个条件始终会获胜,但我想搜索集合并在 while 循环中找到搜索中短语的第一次出现(与标记中的位置相关)后结束搜索.
<HTML>
<head>
</head>
<body>
<script>
function getAppDecision(){
var myCollection = document.getElementsByClassName('main');
var i = myCollection.length;
console.log(" myCollection.length : " + i);
while(i--) {
if (myCollection[i].innerText.search(/opened accounts/i) > -1) {
console.log("==> spot 1 - open accounts");
return;
}
if (myCollection[i].innerText.search(/being reviewed/i) > -1) {
console.log("==> spot 2 - being reviewed");
return;
}
if (myCollection[i].innerText.search(/verify your funding account/i) > -1) {
console.log("==> spot 3 - verify");
return;
}
}
};
</script>
<div class="main">
<span id="firstSpan">
<p> testing Being Reviewed</p>
<p> testing Opened Accounts</p>
<p> testing have Verify YOUR Funding account</p>
</span>
</div>
<script>
getAppDecision();
</script>
</body>
</html>
最佳答案
您的myCollection
将无法获得您正在查找的值。您可能需要更改代码以实现以下目的:
var myCollection = [];
document.querySelectorAll('#firstSpan p')
.forEach((elem) => myCollection.push(elem.innerText));
那么,您可以使用find()
:
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
它将在第一个满足条件的元素处停止。
你可以这样做:
var result = myCollection.find((item) => {
return (item.search(/opened accounts/i) > -1)
|| (item.search(/being reviewed/i) > -1)
|| (item.search(/verify your funding account/i) > -1);
});
之后,根据您的示例,结果
应具有值testing Being Reviewed
。
关于javascript - 如何在 JavaScript 集合中搜索多个短语之间的第一次出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51905495/