【问题标题】:jscodeshift convert forEach to for loopjscodeshift 将 forEach 转换为 for 循环
【发布时间】:2021-12-11 00:36:37
【问题描述】:

我是 jscodeshift 和 AST 的新手,但我正在尝试对现有的 forEach 循环进行转换,并将它们转换为常规的 for 循环。

我想隐藏以下内容:

[
    `foo`,
    `bar`
].forEach(test => {
    console.log(test);
});

到这里:

for(const test of  [`foo`, `bar`]) {
  console.log(test);
}
export default (file, api) => {
  const j = api.jscodeshift;
  const root = j(file.source);

  // What do I do here to transform the forEach to a regular for loop?

  return root.toSource();
};

我一直在浏览一些文档并进行搜索,但我找不到这样做的方法。

【问题讨论】:

    标签: javascript jscodeshift


    【解决方案1】:

    这就是我要找的。​​p>

    root.find(j.CallExpression, {
        callee : {
            property : {
                name : "forEach"
            }
        }
    })
    .replaceWith(path => {
        // Hangles foo.forEach() and [1,2].forEach()
        const expression = path.value.callee.object.name ? j.identifier(path.value.callee.object.name) : j.arrayExpression(path.value.callee.object.elements);
    
        return j.forOfStatement(
          j.variableDeclaration(
                "const",
                path.value.arguments[0].params
          ),
          expression,
          path.value.arguments[0].body
        )
    });
    

    【讨论】: