【发布时间】:2021-04-12 23:21:56
【问题描述】:
我需要根据不同的条件将两个键/值对推送到一个数组中。
第一个键/值的条件:只有以数字开头的段落。
第二个键/值的条件:第一个键/值对之后的所有段落(直到下一个以数字开头的段落)。
这里是html示例:
<div class="someclass">
<p><strong>1. Some text</strong></p>
<p>Some text related to 1.</p>
<p>Some other <a href="/someurl"><strong> text</strong></a> related to 1.</p>
<p><strong>2. Some other text</strong></p>
<p>Some text related to 2.</p>
<p><strong>3. Can you send me a catalog?</strong></p>
...
</div>
我只能用这个 javascript 代码获得第二个键/值对的一个段落:
var array = [];
var allParagraphs = document.querySelectorAll("someclass p");
for (i = 0; i < allParagraphs.length; i++) {
if (/^\d/.test(allParagraphs[i].innerText) === true) {
array.push({
"key1": allParagraphs[i].innerText,
"customText": {
"key2": allParagraphs[i + 1].innerText
}
});
}
}
我得到的输出是这样的:
[{key1: "1. Some text", customText: {key2: "Some text related to 1."}},{key1: "2. Some text", customText: {key2: "Some text related to 2."}},{...}]
我需要得到这样的东西:
[{key1: "1. Some text", customText: {key2: "Some text related to 1. Some other text related to 1."}},{key1: "2. Some text", customText: {key2: "Some text related to 2."}},{...}]
【问题讨论】:
标签: javascript arrays for-loop if-statement