繁体   English   中英

比较两个以上值的最佳方法是什么?

[英]Whats the best way to compare more than two values?

我的文档上有四个div,只要其中至少两个具有相同的文本内容,我就想执行一些代码。

我在寻找不包含手动比较每个div文本内容与其他每个divs文本内容的解决方案时遇到了麻烦

while(div1.textContent === div2.textContent || div1.textContent === div3.textContent || ....)

有一个简单的方法吗?

-编辑HTML

 <div class="container"> <h2>Answers</h2> <div class="row"> <div class="col-md option" id="option1"> Answer </div> <div class="col-md option" id="option2"> Answer </div> <div class="col-md option" id="option3"> Answer </div> <div class="col-md option" id="option4"> Answer </div> </div> </div> 

将div保存到唯一的集合中,然后创建其文本内容的Set 如果Set的大小小于集合的长度,则必须有匹配的内容。

 test("foo"); test("bar"); function test(cls) { var divs = document.querySelectorAll(`.${cls}`); var set = new Set(Array.from(divs, el => el.textContent)); if (set.size < divs.length) { console.log(`'${cls}' found matching content`); } else { console.log(`'${cls}' did not find matching content`); } } 
 .foo, .bar { display: inline-block; } .foo { color: blue; } .bar { color: red; } 
 <div class="foo">1</div> <div class="foo">2</div> <div class="foo">3</div> <div class="foo">1</div> <hr> <div class="bar">1</div> <div class="bar">2</div> <div class="bar">3</div> <div class="bar">4</div> 

您可以执行以下操作:

const textArray = Array.from(document.querySelectorAll('.option'), el => el.innerText);

for(let el of textArray) { 
      const filtered =  textArray.filter(item => item === el);
      if (filtered.length > 1) {
           doSomething();
           break; // can be removed if you want to do continue the loop
      }
}

这是类似于回调的答案的另一种方法。

选择所有带有textContent的元素。 根据是否存在2个或多个过滤textContent。

 //select all elements, getting only their text content let options = Array.from(document.getElementsByClassName("option")).map(function(options){ return options.textContent; }); //filter by whether 2 or more exist multipleOptions = options.filter((item, i)=>{ const iOf = options.indexOf(item); return(iOf != i && iOf != -1);//if 2 or more of item, keep it }); //output.. console.log("number of options with 2 or more of the same text content:", multipleOptions.length); console.log("boolean, contains 2 or more of the same content?", multipleOptions.length > 0); 
 <div class="container"> <h2>Answers</h2> <div class="row"> <div class="col-md option" id="option1"> Answer </div> <div class="col-md option" id="option2"> Answer </div> <div class="col-md option" id="option3"> test </div> <div class="col-md option" id="option4"> test </div> </div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM