javascript - 我如何将这个 for 循环变成 forEach 循环?

标签 javascript loops for-loop foreach

大家好^^ 如果之前有人问过这个问题,我深表歉意(尽管我自己找不到以前发布的类似问题......)。另外,请允许我提前为这个问题的简单性道歉。

这是一个类似于命运之轮的简单网页游戏。随机报价是通过 js 脚本生成的,用户应该通过屏幕键盘按键来猜测。但是,目前我无法将用户点击与引用文本内容的点击进行比较;它返回“未定义”。

我理解(在阅读了这里的一些问题之后) document.querySelectorAll('.letters') 返回“undefined”的原因是因为它是一个数组,并且可能需要一个 forEach 循环,而不是一个for 循环。

但是,有没有办法增强此 for 循环以将按钮单击事件目标值与 document.querySelectorAll('.letters') 数组值进行比较?如果没有,我该如何将其编写为 for every 循环?我在最后一个小时左右尝试重新编写它,但没有成功:/

是否无法将其包含在具有事件监听器的函数中?

非常感谢您的宝贵时间。

问题代码:

qwerty.addEventListener('click', function (event) {
  if ( event.target.tagName === "BUTTON" ) {
       event.target.className = "chosen";
      for( let i = 0; i < letters.length; i++ ) {
          if( event.target.innerText === letters.textContent.toLowerCase() ) {
              letters.className = 'show';
              matched += 1;
          }
       }
    }
 });

完整代码:

//Keyboard and game element variables

const qwerty = document.getElementById('qwerty');
const phrase = document.getElementById('phrase');
const keyLetters = document.querySelectorAll('.keyrow button').innerText;

//hidden letters of phrase
const letters = document.querySelectorAll('.letters');

//Game score 

const missed = 0;
const matched = 0;

//Start button (hides start screen overlay and begins game)
const startGame = document.querySelector('.btn_reset');

startGame.addEventListener('click', function () {
    document.querySelector('.start').style.display = 'none'; 
});


//Game quotes

const quotes = [
["René Descartes"        , "I think therefore I am"],
["Friedrich Nietzsche"   , "What does not kill me makes me stronger"],
["Socrates"              , "The unexamined life is not worth living"],
["Sir Winston Churchill" , "If you are going through hell keep going"],
["Winnie the Pooh"       , "Doing nothing often leads to the very best of something"],
["Aldous Huxley"         , "Never have so many been manipulated so much by so few"],
["Albert Einstein"       , "The most beautiful experience we can have is the mysterious"]
];


//Generate random quote

const getRandomPhraseAsArray = () => {
    //create random number between 1 - 7 for quote selection
    let randNum = Math.floor( Math.random() * (quotes.length) );
    //retrieve object value (quote) with random number
    let randQuote = quotes[randNum][1];
    //select the ul .phrase div
    const ul = document.querySelector('#phrase ul');
    //Append to li element created in const li 
    randQuote = randQuote.toString().split("");
    //iterate though each string value in randQuote, create an li element
    //then set the innerText of the li to the string value

    for( let i = 0; i < randQuote.length; i++ ) {
        const li = document.createElement("li");
        ul.appendChild(li);
        li.innerText = randQuote[i]; 
            if ( randQuote[i] != " " ) {
                li.className = "letter";
            } else {
                li.className = "space";
            }
        };
}; 

getRandomPhraseAsArray();

//keypress function

qwerty.addEventListener('click', function (event) {
    if ( event.target.tagName === "BUTTON" ) {
         event.target.className = "chosen";
        for( let i = 0; i < letters.length; i++ ) {
             if( event.target.innerText === letters.textContent.toLowerCase() ) {
                 letters.className = 'show';
                 matched += 1;
             }
        }
    }
});

最佳答案

已修复。 StackSlave 是正确的。迭代数组需要一个 for/of 循环。

qwerty.addEventListener('click', function (event) {
if ( event.target.tagName === "BUTTON" ) {
     event.target.className = "chosen";
    for( const letter of letters ) {
         if( event.target.innerText === letter.textContent.toLowerCase() ) {
             letter.className = 'show';
             matched += 1;
         }
    }
}

});

关于javascript - 我如何将这个 for 循环变成 forEach 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60444725/

相关文章:

javascript - 无法读取菜单上 null 的属性 'addEventListener'

javascript - jQuery 按钮来检查所有复选框问题

python - 为什么这两个循环的速度完全相同?

java - 在 python 中搜索项目列表的更好方法

javascript - 我正在使用 Laravel 5.4 : and js not loading in blade during editing

javascript - 在图像 html 旁边键入文本

c++ - 如何保持循环直到输入非整数

java - 在数组中搜索一个值,如果不存在则存储它

Java - 同时执行两个相应的for循环

java - 将 while 循环更改为 for 循环