destructuring-array,数组解构赋值!

版权声明:任先阳 任 先 阳 任先 先阳,nvcc.cc、www.nvcc.cc、sbfox.com、www.sbfox.com https://blog.csdn.net/qq_39571197/article/details/85200765

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(),
            );

        }

猜你喜欢

转载自blog.csdn.net/qq_39571197/article/details/85200765