我试图创建一个forEach方法,以获得每个数组的子字符串



我有一个像这样的文本文件:sciif .png, posed.png, birdA.png, dolphin.png, horse.png, shake.png, lot .png, basement.png, revenge .png, friend.png

我将该文件导入到js文档中并尝试从该文件中创建一个数组,然后使用forEach()方法为每个数组元素创建substr()以取下'.png'(因此输出将是sciFi, posed, birdA, dolphin等)。

下面是我的代码:

<!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();
}

我知道我可能要走了,但我正试图弄清楚要在myFunction()中放入什么才能使其工作。有什么建议吗?

这是一种现代的写法:

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);
}

原始代码片段中的错误与您如何调用forEach:

有关。
const images = [];
myPix.forEach(myFunction, function myFunction(item) {
var buttVal = myPix.substr(0,myPix.indexOf("."));
images.push(buttVal);
});

最新更新