zoukankan      html  css  js  c++  java
  • 还原数组

    const parser = require("@babel/parser");
    const traverse = require("@babel/traverse").default;
    
    // 将js代码转换成AST
    // const { parse } = require("@babel/parser");
    // 用来遍历AST中的节点
    // const traverse = require("@babel/traverse").default;
    // AST转换成js
    const generator = require("@babel/generator").default;
    // 用来判断节点类型和生成新的节点
    const types = require("@babel/types");
    
    
    const jscode = `
    
    var a = [1,2,3,[1213,234],{"code":"666"},window];
    b = a[1] + a[2] + a[3];
    c = a[4];
    d = a[5];
    
    `;
    let ast = parser.parse(jscode);
    
    
    
    const replaceArrayElements =
    {//数组还原
        VariableDeclarator(path) {
            let { node, scope } = path;
            let { id, init } = node;
            if (!types.isArrayExpression(init)) return;
    
            const binding = scope.getBinding(id.name);
            if (!binding || !binding.constant) {
                return;
            }
    
            for (let referPath of binding.referencePaths) {
                let { node, parent } = referPath;
                if (!types.isMemberExpression(parent, { object: node }) || !types.isNumericLiteral(parent.property)) {
                    return;
                };
            }
    
            for (let referPath of binding.referencePaths) {
                let { parent, parentPath } = referPath;
                let index = parent.property.value;
                parentPath.replaceWith(init.elements[index]);
            }
            path.remove();
        },
    }
    
    traverse(ast, replaceArrayElements);
    
    
    let { code } = generator(ast);
    
    console.log(code);
  • 相关阅读:
    class线程信息
    Class 文件简介
    JVM对象及垃圾回收处理
    jvm体系结构
    查找

    二叉树
    队列


  • 原文地址:https://www.cnblogs.com/angdh/p/15757916.html
Copyright © 2011-2022 走看看