Gia*_*ini 1 javascript ecmascript-6
我认为reduce可能会帮助我用最少的代码解决对节点列表的简单检查,但我无法确定我是否无法使其工作,或者我忽略了一些限制,例如reduce“它不适用于节点列表”。
这是我到目前为止所尝试的:
网页:
<input class="form-check-input typeOfRepetition" type="radio" id="r1">
<input class="form-check-input typeOfRepetition" type="radio" id="r2">
<input class="form-check-input typeOfRepetition" type="radio" id="r2">
Run Code Online (Sandbox Code Playgroud)
JS
typeOfRepetition__all= document.querySelectorAll('.typeOfRepetition')
const reducer = (acc, currV) => acc + (currV.checked ? 1 : 0)
const choiceChecked = els.typeOfRepetition__all.reduce(reducer);
if (choiceChecked) {
//...do some stuff
}
Run Code Online (Sandbox Code Playgroud)
我尝试了在MDN 沙箱内使用reduce 和三元运算符检查的方法,效果很好,即:
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + ( currentValue % 2 ? 1 : 0);
// 1 + 2 + 3 + 4 becomes 1 + 0 + 1 + 0 = 2
console.log(array1.reduce(reducer));
Run Code Online (Sandbox Code Playgroud)
但我不明白为什么它不适用于我最初的想法。forEach与该节点列表/数组配合得很好,所以我希望它reduce也能正常工作。
任何帮助,将不胜感激。
编辑Array.from():在发布之前,我尝试在由此产生的节点列表上使用querySelectorAll它,它让我更进一步:reduce有效,但不是计算一个干净的数字输出(即零或一个响应),它给了我类似的东西
console.log('choiceChecked:', choiceChecked)
// choiceChecked: [object HTMLInputElement]10
// or
// choiceChecked: [object HTMLInputElement]00
Run Code Online (Sandbox Code Playgroud)
也许我应该停止在深夜编码:P
是的,您需要Array.from在节点列表上使用才能reduce在其上使用。
[object HTMLInputElement]10从减速器获得的原因是它第一次运行时acc被设置为第一个节点(而不是第一个节点的checked属性)。从那时起,它似乎尝试将0s 和1s 与该节点作为 strings连接起来。强制转换为字符串的第一个节点是'[object HTMLInputElement]'。然后与其他两个值连接起来'[object HTMLInputElement]10'。
您需要将初始值传递0给reduce:
Array.from(typeOfRepetition__all).reduce(reducer, 0);
Run Code Online (Sandbox Code Playgroud)
这样, 的初始值acc将是0,而不是第一个节点。另请注意,它现在将迭代三次,而不仅仅是两次。
但是,您似乎只是想计算某个类别的选中单选按钮的数量。为什么不直接做:
document.querySelectorAll('.typeOfRepetition:checked').length
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2946 次 |
| 最近记录: |