当我偶然发现一个问题时,我正在研究一些 Javascript 代码:是否有任何方法可以在任何 javascript 文件中找到 objects
的数量, 然后将它们打印出一个函数?
我在互联网上没有找到任何可以解决这个问题的答案,我怀疑这是可能的,但如果有人有想法,我会有兴趣可以看看。
代码示例,如果这没有意义:
var str = "Hello World!";
var num = 3.14;
var obj = {};
function printOutObjects() {
var objs = [];
// Find objects in script...
console.log(objs);
}
最佳答案
好吧,最终一切都是 window
对象的一部分,因此作为理论练习,您可以使用以下内容,但它会让您稍微比您预想的多(并可能使您的计算机崩溃):
var str = "Hello World!";
var num = 3.14;
var obj = {};
function printOutObjects() {
var objs = [];
objs.push(window);
recurseObj(window, objs);
console.log(objs);
}
function recurseObj(o, objs) {
if(typeof(o) == "undefined" || o == null || typeof(o) == "string" || typeof(o) == "number") {
return;
}
for(var c in o) {
// handle security exceptions and whatever else may come up
try {
// stop computer crashing
if(objs.length > 300) {
return;
}
else {
var obj = o[c];
// Ensure its not already in the results
if(objs.indexOf(obj) == -1) {
objs.push(obj);
recurseObj(obj, objs);
}
}
} catch(e){}
}
}
printOutObjects();
虽然我完全不确定您为什么要这样做,如果您想查看页面中的内容,您可以在控制台中登录 window
并向下钻取.
关于javascript - 获取 Javascript 文件中所有对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27091888/