循环获取所有元素,在哪里使用forEach?
Looping to get all elements, where to utilize forEach?
我正在对 return 值进行网络抓取,但是我不确定如何输出所有元素。
例如 html 看起来像这样:
<input type="radio" name="code" value="111">
<input type="radio" name="code" value="222">
<input type="radio" name="code" value="333">
我正在尝试输出所有值。
function scrapeValues {
const $codes = $('input[name="code"]');
for (const code of $codes.get()) {
const $code = $(code);
const results = $code.val() as string;
codeArray = results.trim();
}
return codeArray
}
目前,我只得到最后一个值 (333)。我在想我需要在某个地方使用 forEach 但我尝试在 $codes.get() 之后使用它但是我收到错误,不确定是因为结束标记在错误的位置还是我需要实施它在别处。
OP 想要利用 Array.prototype.map
after having retrieved e.g. a NodeList
via document.querySelectorAll
which one, before the mapping, needs to make an Array.from
。
顺便说一句,jquery implements its own map
...
console.log(
Array.from(
document.querySelectorAll('[type="radio"][name="code"]')
).map(node => node.value)
);
console.log([
...document.querySelectorAll('[type="radio"][name="code"]')
].map(node => node.value)
);
console.log(
$('[type="radio"][name="code"]')
.map(function () { return this.value; })
.get()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="code" value="111" />
<input type="radio" name="code" value="222" />
<input type="radio" name="code" value="333" />
我正在对 return 值进行网络抓取,但是我不确定如何输出所有元素。
例如 html 看起来像这样:
<input type="radio" name="code" value="111">
<input type="radio" name="code" value="222">
<input type="radio" name="code" value="333">
我正在尝试输出所有值。
function scrapeValues {
const $codes = $('input[name="code"]');
for (const code of $codes.get()) {
const $code = $(code);
const results = $code.val() as string;
codeArray = results.trim();
}
return codeArray
}
目前,我只得到最后一个值 (333)。我在想我需要在某个地方使用 forEach 但我尝试在 $codes.get() 之后使用它但是我收到错误,不确定是因为结束标记在错误的位置还是我需要实施它在别处。
OP 想要利用 Array.prototype.map
after having retrieved e.g. a NodeList
via document.querySelectorAll
which one, before the mapping, needs to make an Array.from
。
顺便说一句,jquery implements its own map
...
console.log(
Array.from(
document.querySelectorAll('[type="radio"][name="code"]')
).map(node => node.value)
);
console.log([
...document.querySelectorAll('[type="radio"][name="code"]')
].map(node => node.value)
);
console.log(
$('[type="radio"][name="code"]')
.map(function () { return this.value; })
.get()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="code" value="111" />
<input type="radio" name="code" value="222" />
<input type="radio" name="code" value="333" />