此“计数器”的目标是查看“ ToCount”字符串中有多少个不同的单词。为此,它使ToCount成为数组,然后遍历元素,检查它们是否已经存在,如果不存在,则将它们添加到那里。

循环后,ToCountArr2保持为空,长度为0。为什么会发生这种情况,我该怎么办?

我运行了一个调试器,发现没有元素添加到第二个列表中,好像如果第一个数组的第i个元素已经在第二个数组中,则“ if”控件中没有任何内容。

function counter(){
    var ToCount = document.getElementById("demo").value; //the contents of a textbox
    var ToCountArr1 = ToCount.split(" ");
    var ToCountArr2 = new Array;
    var i = 0;
    var lengthToCountArr1 = ToCountArr1.length;
    var wordToPush;
    while (i < lengthToCountArr1){
    if(ToCountArr2.includes(ToCountArr1[i] === false)) {
            wordToPush = ToCountArr1[i];
            ToCountArr2.push(wordToPush);
        }
        i = i + 1;
    }
    alert(ToCountArr2.length);
}

最佳答案

问题在于此行if(ToCountArr2.includes(ToCountArr1[i] === false))。在这里,花括号必须在ToCountArr1[i]之后,其中ToCountArr1[i] === false)这行正在检查ToCountArr1中的值是true还是false。

这条线

if(ToCountArr2.includes(ToCountArr1[i] === false))将被评估为

if(ToCountArr2.includes(true/false))
取决于ToCountArr1[i] === false)的结果



function counter() {
  var ToCount = document.getElementById("demo").value; //the contents of a textbox
  var ToCountArr1 = ToCount.split(" ");
  var ToCountArr2 = new Array;
  var i = 0;
  var lengthToCountArr1 = ToCountArr1.length;
  var wordToPush;

  while (i < lengthToCountArr1) {
    if (ToCountArr2.includes(ToCountArr1[i]) === false) {
      wordToPush = ToCountArr1[i];
      ToCountArr2.push(wordToPush);
    }
    i = i + 1;
  }
  console.log(ToCountArr2.length);
}

counter()

<input type='text' id='demo' value='Test Values'>





您可以将if (ToCountArr2.includes(ToCountArr1[i]) === false) {最小化,方法是将其替换为

if (!ToCountArr2.includes(ToCountArr1[i])) {

关于javascript - 为什么第二个数组保持为空?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55712691/

10-11 22:10