最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - FormData.delete() doesn't work correctly inside a for loop - Stack Overflow

programmeradmin1浏览0评论

var data = new FormData(document.getElementsByTagName("form")[0]);
for(var [key, value] of data.entries()) {
	if (!value) {
    data.delete(key);
    console.log(data.getAll(key));
  }
}
<form>
  <input name="x[1]" type="text" value="">
  <input name="y[2]" type="text" value="">
  <input name="z[3]" type="text" value="">
  <input name="a[4]" type="text" value="">
</form>

var data = new FormData(document.getElementsByTagName("form")[0]);
for(var [key, value] of data.entries()) {
	if (!value) {
    data.delete(key);
    console.log(data.getAll(key));
  }
}
<form>
  <input name="x[1]" type="text" value="">
  <input name="y[2]" type="text" value="">
  <input name="z[3]" type="text" value="">
  <input name="a[4]" type="text" value="">
</form>

I have this form and I get its data using FormData() then I remove the empty values which is all of them but there is always those random not deleted keys even while it is empty

Share Improve this question edited Jun 22, 2021 at 16:26 adiga 35.3k9 gold badges65 silver badges87 bronze badges asked Jul 20, 2019 at 17:11 Joe DoeJoe Doe 5732 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 18

Even if you remove the if logic and just log the key and delete it, only the first and the third keys are deleted. This is pretty weird. Simultaneously deleting and looping the same collection of keys is probably causing it to behave this way:

var data = new FormData(document.querySelector("form"));

for(var [key, value] of data.entries()) {
    console.log(key); // only 2 keys get logged
    data.delete(key);
}

console.log(Array.from(data.keys())) // still 2 keys are left
<form>
  <input name="x[1]" type="text" value="">
  <input name="y[2]" type="text" value="">
  <input name="z[3]" type="text" value="">
  <input name="a[4]" type="text" value="">
</form>

One fix would be to convert the iterator to an array of entries using Array.from(). Now when the keys are deleted from FormData, the array won't affected:

var data = new FormData(document.querySelector("form"));

for(var [key, value] of Array.from(data.entries())) {
    console.log(key); // every key gets logged now
    data.delete(key);
}

console.log(Array.from(data.keys())) // all are deleted
<form>
  <input name="x[1]" type="text" value="">
  <input name="y[2]" type="text" value="">
  <input name="z[3]" type="text" value="">
  <input name="a[4]" type="text" value="">
</form>

发布评论

评论列表(0)

  1. 暂无评论