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

时间:2018-03-11 16:51:14

标签: javascript compare

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

我无法找到不包含手动将每个div文本内容与其他div文本内容进行比较的解决方案

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>

3 个答案:

答案 0 :(得分:1)

将您的div保存到一个唯一的集合,然后创建一个userChoice != "rock" && userChoice != "paper" && "scissors" 的文本内容。如果userChoice != "rock" && userChoice != "paper" && userChoice != "scissors" 的大小小于集合的长度,则必须有匹配的内容。

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`);
  }
}

答案 1 :(得分:1)

您可以执行以下操作:

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
      }
}

答案 2 :(得分:0)

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

使用textContent选择所有元素。过滤textContent是否存在2个或更多。

&#13;
&#13;
//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);
&#13;
<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>
&#13;
&#13;
&#13;