[英]Javascript array value compare
I am checking each checkbox status (2 elements in total). 我正在检查每个复选框的状态(总共2个元素)。
var checked = [];
document.querySelectorAll('.checkbox').forEach(function(e,i){
checked.push(e.checked)
})
Now checked value could be 现在检查值可能是
(2) [true, true]
or 要么
(2) [true, false]
or 要么
(2) [false, true]
or 要么
(2) [false, false]
I am now checking it with a little bit manual way 我现在用一点手动方式检查它
if(checked[0] && check[1]) { ... }
If I have more elements, I have to add them manually like 如果我有更多元素,则必须手动添加它们,例如
if(checked[0] && check[1] && check[2]) { ... }
I am seeking a better way to polish my code, so I don't need to manually add array values to compare. 我正在寻找一种改进代码的更好方法,因此不需要手动添加数组值进行比较。 Thanks 谢谢
Use every
and Array.from
使用every
和Array.from
var checked = [];
var allCheckboxes = document.querySelectorAll('.checkbox');
var allChecked = Array.from( allCheckboxes ).every( s => s.checked )
You can use Array.reduce
to do that like this 您可以使用Array.reduce
这样做
const pass = [true, true, true] const passNot = [true, false, true] const reducer = (isPassing, value) => { if (value === false) return false else return isPassing } console.log('yay', pass.reduce(reducer, true)) console.log('nay', passNot.reduce(reducer, true))
You are tryng to combine an array of values into a single one, thats what the reduce
method does. 您正在尝试将值数组组合为单个值,这就是reduce
方法的作用。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
let result = document.querySelectorAll('.checkbox')
.map( box => box.checked ) // get an array of boolean
.reduce ( (bool, res) => return bool && res /*all checkboxes must be checked */, true /* initial value */ );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.