Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

278
Vistas
I am attempting to create a forEach method in order to get a substring of each array

I have a text file that looks like this: sciFi.png, posed.png, birdA.png, dolphin.png, horse.png, shake.png, loft.png, basement.png, avenger.png, friend.png

I'm importing that file to a js doc and attempting to create an array out of that file and then use the forEach() method to create a substr() for each array element to take off the '.png' (so the output would be sciFi, posed, birdA, dolphin and so on).

Here is my code so far:

html

<!DOCTYPE html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <title>My fabulous document</title>
</head>
<body>
  <div id="demo">
    <h2>The XMLHttpRequest Object</h2>
    <button type="button" onclick="loadDoc()">change content</button>
  </div>
</body>
<script type="text/javascript" src="getImgButton.js">
</script>
</html>

js

function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        pix = this.responseText;
        myPix = pix.split(",");      
        myPix.forEach(myFunction);
        function myFunction(myPix) {
         // var buttVal = myPix.substr(0,myPix.indexOf("."));
        }
      }
    };
    xhttp.open("GET", "imageList.txt", true);
    xhttp.send();
  }

I know I'm probably way off but I'm trying to figure out what to put in myFunction() to get this to work. Any suggestions?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here's a modern way to write this:

async function loadDoc() {
  const response = await fetch('imageList.txt');
  const body = await response.text();
  const images = body.split(',').map(
    fileName => fileName.split('.')[0]
  );
  console.log(images);
}

The errors in your original snippet has to do with how you called forEach:

        const images = [];
        myPix.forEach(myFunction, function myFunction(item) {
          var buttVal = myPix.substr(0,myPix.indexOf("."));
          images.push(buttVal);
        });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda