javascript – 如何根据内容而不是名称来查看变量?

我需要将包含特定字符串或整数值的所有变量替换为其他值.例如,替换包含gn.frwithnlg.com的所有变量的值.

在windbg(windbg附加到Web浏览器进程),这可以这样实现:

.foreach (hit {s -[1]a 0 L?80000000 "gnl.fr"}) {ea ${hit} "nlg.com"}

但是,它会不时地清除关键值,从而导致Web浏览器崩溃.
绝对可以在JavaScript级别进行,而不是处理Web浏览器二进制文件.

我不想只为全局变量做这件事,但是到处都是可能的(我的意思是包括来自其他JavaScript函数的局部变量,而不是当前正在调试的函数).

问题是我甚至不知道如何搜索当前范围之外的变量.

投票结束前不清楚请注意所有标签!

最佳答案 以递归方式遍历每个对象及其子对象.修改特定的孩子.

要防止与递归相关的错误,您可以指定要进入子项的子级的级别数.

以下示例的注释中的进一步说明:

/**
Replace all strings from @inObj matching @toReplace with @replaceWith
*/

var replace = function(inObj, toReplace, replaceWith, optionalArguments){



  console.log("before", inObj);

  var recursion = function(obj, recursionLevel){

    if(typeof recursionLevel === 'undefined'){
      recursionLevel = 0;
    }

    recursionLevel++;

    if(typeof optionalArguments !== 'undefined'){
      if( typeof optionalArguments.maxRecursionLevel !== 'undefined' && recursionLevel > optionalArguments.maxRecursionLevel ){ // simply return the object if maxRecursionLevel reached
        return obj;
      }
    }

    for(var b in obj) { 
      if(typeof obj.hasOwnProperty !== 'undefined' && obj.hasOwnProperty(b)){
        if(typeof obj[b] === "string"){ // element is a string - here we do the actual work: replacing the strings
          obj[b] = obj[b].replace(toReplace, replaceWith);
        }else if(typeof obj[b] === "object" && obj[b]){ // element is an object - call as an object "recursively"
          obj[b] = recursion(obj[b], recursionLevel);
        }
      }
    }
    return obj;
  }

  inObj = recursion(inObj);
  console.log("after", inObj);
  return inObj;
}


/**
example for a test object
*/
var testObj = {
  a: "abc",
  b: "xyz",
  c: {
    aa: {
      aaa: "abc",
      bbb: "abc"
    },
    bb: "abc"
  },
  d: {
    aa: "abc"
  }
};

replace(testObj, /bc/i, "X", {maxRecursionLevel:2}); // for two levels
//replace(testObj, /bc/i, "X");  // for all levels



/**
example for the global scope
*/
//replace(window, /gnl.fr/i, "nlg.com");
点赞