我有以下代码,其中使用FileReader读取base64版本的文件。变量formValues包含属性“ images”,该属性包含文件数组(即文件信息和本地url)。我将images属性更新为包含base64字符串,而不是该方法的end处的Files。但是,方法开头的控制台日志显示该更新。当我在末尾注释掉更新时,开始的控制台日志再次显示“文件”。多么奇怪。我在做什么错?
const confirm = () => {
console.log("form values in confirm");
// this prints the base64 string when formValues["images"] = images
// is present at the end.
// Otherwise it prints the Files.
console.log(formValues.images);
let images = [];
for (let i = 0; i < formValues.images.length; i++) {
var reader = new FileReader();
reader.onload = function(e) {
images.push(e.target.result);
console.log('images base 64');
console.log(images);
};
reader.readAsDataURL(formValues.images[i].file);
}
formValues["images"] = images;
console.log("values after adding images");
console.log(formValues);
};
这是因为数组是可变的,这意味着它们的值在创建后可以更改。