destructuring-array,陣列解構賦值!
阿新 • • 發佈:2019-01-03
BUG未知...
function destructuringArray(target, arr, exp) { try { exp = exp.replace(/((\.{3})?\w+)/g, ($0, $1) => { if (!window.isNaN(+$1[0])) throw ('變數名不能以數字開頭'); return `"${$1}"`; }); exp = JSON.parse(exp); } catch (e) { console.log(e); } function main(target, arr, expArr) { expArr.forEach((exp, i) => { let currentValue = arr ? arr[i] : undefined; /* 遞迴處理 */ if (Array.isArray(exp)) { main(target, currentValue, exp); return; }; /* 處理展開操作符 */ if (exp.startsWith('...')) { if (i !== expArr.length - 1) { throw ('展開運算子,只能在最後一個變數使用'); } exp = exp.slice(3); target[exp] = arr.slice(i); return; } target[exp] = arr === undefined ? undefined : currentValue; }); }; main(target, arr, exp); } const test = {}; const data = [1, 2, [3, [4, [5, 6, 7, [8]]]]]; destructuringArray(test, data, '[a,b,[c,[d,[e,...gg]]]]'); /**/ { const [a, b, [c, [d, [e, ...gg]]]] = data; console.log( a === test.a, b === test.b, c === test.c, d === test.d, e === test.e, gg.toString() === test.gg.toString(), ); }