indexの宣言がletかvarかで結果が変わる件を難しく書いた
jsらしい気がする。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
const main = () => { const p = console.log; const copyFromBtoA = (a, b) => { for (const k of Object.keys(b)) { const v = b[k]; a[k] = v; } }; const getPromiseArr_let = () => { const ps = []; for (let i = 0; i < 5; i++) { ps.push(new Promise(resolve => { setTimeout(() => { resolve(i); }, 0); })); } return ps; }; const getPromiseArr_var = () => { const ps = []; for (var i = 0; i < 5; i++) { ps.push(new Promise(resolve => { setTimeout(() => { resolve(i); }, 0); })); } return ps; }; const doPromiseAll = (ps, func) => { Promise.all(ps).then(results => { func(results); }); }; const sub = () => { const psLet = []; const psVar = []; copyFromBtoA(psLet, getPromiseArr_let()); copyFromBtoA(psVar, getPromiseArr_var()); doPromiseAll(psLet, p); doPromiseAll(psVar, p); }; sub(); }; main(); |
1 2 |
[ 0, 1, 2, 3, 4 ] [ 5, 5, 5, 5, 5 ] |