Home > Net >  forEach loop on an array of objects
forEach loop on an array of objects

Time:10-07

I've been trying to get it to go through all the for loops but it always says that the array.. textLines/messages is undefined whenever I try to get any element within the array.

I want to get the whole object and use split("") to get each letter from the text. whenever I look at the console log trying to get anything from the array (even its length) says it's undefined but whenever I just put the array in there it shows the array of objects normally. how would I be able to make the define the elements (objects) within the array??

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

})

CodePudding user response:

There are two solutions to this problem:

  1. Either you can just send the array in say function like:

    say([...])

  2. Or you can change the parameters you are accepting in the say function like:

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

  • Related