繁体   English   中英

forEach 在对象数组上循环

[英]forEach loop on an array of objects

我一直在尝试通过所有 for 循环将其获取到 go,但它总是说数组 .. textLines/messages 是未定义的,每当我尝试获取数组中的任何元素时。

我想获取整个 object 并使用 split("") 从文本中获取每个字母。 每当我查看控制台日志试图从数组中获取任何内容(甚至它的长度)时,它都说它是未定义的,但每当我只是将数组放在那里时,它都会正常显示对象数组。 我怎样才能定义数组中的元素(对象)?

function say(messages = [{text: ' ', speed: 90, pause: false, colour: ['RED//BLUE']}]){        
  let alphabets = [];                                  
  let textLines = messages

  console.log(textLines.length)
  
  textLines.forEach((line, i) => {                       
    if (i < textLines.length - 1)  line.text += " ";        
    
    console.log(typeof textLines[1])
    line.text.split("").forEach((alphabet) => {        
      let span = document.createElement("span");
        span.textContent = alphabet;                       
        textContainer.appendChild(span);
        alphabets.push({                                  
          span: span,
          isSpace: alphabet === " " && !line.pause,
          delayAfter: line.speed,
          classes: line.classes || []
        });
    });
  });

  function revealLetter(list) {
    let nextLetter = list.splice(0, 1)[0];        
    nextLetter.span.classList.add("revealed");        
    nextLetter.classes.forEach((c) => {
        nextLetter.span.classList.add(c);       
    });
    let delay = nextLetter.isSpace && !nextLetter.pause ? 0 : nextLetter.delayAfter;        
    
    if (list.length > 0) {
        setTimeout(function () {         
          revealLetter(list);
        }, delay);      // the delay is the talking speeds
    }
  }

  setTimeout(() => {        // to start the loop
    revealLetter(alphabets);   
  }, 600)


}


say({             // can change what's said, the colour of text, the speed its displayed and if there's a pause (4 things)
  messages: [
    {text: 'Literally what does that even mean???',
    speed: talkingSpeeds.fast,
    pause: false,
    },

    {text: 'Like. what?',
    speed: talkingSpeeds.normal,
    pause: true
    },
    
    {text: 'Stop talking.',
    speed: talkingSpeeds.slow,
    pause: true,
    colour: ['red']
    }
  ]

})

这个问题有两种解决方案:

  1. 或者你可以像这样发送数组 function :

    说([...])

  2. 或者您可以更改您在 function 中接受的参数,例如:

    function say({messages = [{text: ' ', speed: 90, pause: false, colour: ['RED//BLUE']}]}) {...}

暂无
暂无

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

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