iterator-invalidation-foreach.html (1374B)
1 <!doctype html> 2 <meta charset="utf-8"> 3 <title>Behavior of iterators when modified within foreach</title> 4 <script src="/resources/testharness.js"></script> 5 <script src="/resources/testharnessreport.js"></script> 6 <link rel="help" href="https://webidl.spec.whatwg.org/#es-forEach"> 7 <link rel="author" title="Manish Goregaokar" href="mailto:manishsmail@gmail.com"> 8 <script> 9 test(function() { 10 let params = new URLSearchParams("a=1&b=2&c=3"); 11 let arr = []; 12 params.forEach((p) => { 13 arr.push(p); 14 params.delete("b"); 15 }) 16 assert_array_equals(arr, ["1", "3"]); 17 }, "forEach will not iterate over elements removed during iteration"); 18 test(function() { 19 let params = new URLSearchParams("a=1&b=2&c=3&d=4"); 20 let arr = []; 21 params.forEach((p) => { 22 arr.push(p); 23 if (p == "2") { 24 params.delete("a"); 25 } 26 }) 27 assert_array_equals(arr, ["1", "2", "4"]); 28 }, "Removing elements already iterated over during forEach will cause iterator to skip an element"); 29 test(function() { 30 let params = new URLSearchParams("a=1&b=2&c=3&d=4"); 31 let arr = []; 32 params.forEach((p) => { 33 arr.push(p); 34 if (p == "2") { 35 params.append("e", "5"); 36 } 37 }) 38 assert_array_equals(arr, ["1", "2", "3", "4", "5"]); 39 }, "Elements added during iteration with forEach will be reached"); 40 </script>