Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript forEach检查所有元素是否为真/假_Javascript - Fatal编程技术网

javascript forEach检查所有元素是否为真/假

javascript forEach检查所有元素是否为真/假,javascript,Javascript,我有几节课 <div class="adiv"></div> <div class="adiv"></div> <div class="adiv cc"></div> <div class="adiv"></div> <div class="adiv"></div> document.querySelectorAll('.adiv').forEach((v, i) =>

我有几节课

<div class="adiv"></div>
<div class="adiv"></div>
<div class="adiv cc"></div>
<div class="adiv"></div>
<div class="adiv"></div>

document.querySelectorAll('.adiv').forEach((v, i) => {
    console.log(v.classList.contains('cc'));
});
用于检查数组中的每个元素是否都传递谓词

[1, 2, 3].every((num) => num > 0); // true
因为您使用的是
document.querySelectorAll
,所以需要将它返回的类似数组的对象转换为实际数组

你可以用这个

综合起来,你会得到:

allCC =
  Array.from(document.querySelectorAll('.adiv'))
    .every((node) => node.classList.contains('cc'));
数组。from(
)。每个(
方法通常都可以工作。不过,在这种情况下,还有另一种相当优雅的方式:

!document.querySelectorAll(".adiv:not(.cc)").length
这将返回类
adiv
显示时没有类
cc
的所有元素的否定长度(
true
,对于
0
false
否则)

另一种方式:

document.querySelectorAll(".adiv").length == document.querySelectorAll(".adiv.cc").length

这会将
.adiv
的数量与两个类的元素数量进行比较。

类似于
Array.from(document.querySelectorAll('.adiv')).every(
..
)。查找方法。抽象大纲:检查每个元素,一旦你找到一个产生
false
的元素,你就可以打破循环,因为你知道不是所有元素都是
true
。或者为什么不只是
!document.queryselectoral('.adiv.cc').length
?@Xufox感谢您的回答!令人惊叹的!!短小clear@Xufox那不是倒退了吗?不应该是
!document.querySelectorAll('.adiv:not(.cc)).length
的目的是检查每个
.adiv
元素是否都有
.cc
类。我避免使用这种速记符号是有原因的。代码背后的意图被掩盖并导致混乱。很好。但是
Array.prototype.slice.call(document.queryselectoral('.adiv'))。每个(…)
都会因为浏览器中的Array.prototype而变得更好support@disstruct,在我链接到的MDN文档中有一个polyfill,此时,
Array.from具有强大的浏览器支持。
document.querySelectorAll(".adiv").length == document.querySelectorAll(".adiv.cc").length