Tengo un archivo de texto que se ve así: sciFi.png, posed.png, birdA.png, dolphin.png, horse.png, shake.png, loft.png, basement.png, avenger.png, friend.png
Estoy importando ese archivo a un js doc e intentando crear una matriz a partir de ese archivo y luego uso el método forEach() para crear un substr() para cada elemento de la matriz para quitar el '.png' (por lo que la salida sería sciFi, posed, birdA, dolphin, etc.).
Aquí está mi código hasta ahora:
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(); }Sé que probablemente estoy muy lejos, pero estoy tratando de averiguar qué poner en myFunction() para que esto funcione. ¿Alguna sugerencia?
Aquí hay una forma moderna de escribir esto:
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); } Los errores en su fragmento original tienen que ver con cómo llamó a forEach :
const images = []; myPix.forEach(myFunction, function myFunction(item) { var buttVal = myPix.substr(0,myPix.indexOf(".")); images.push(buttVal); });