gpt4 book ai didi

JavaScript 迭代对象属性 - 陷入循环引用循环

转载 作者:行者123 更新时间:2023-11-30 15:45:42 25 4
gpt4 key购买 nike

我有一个大对象(它有大约 200 个属性),我想像这样打印它:

[property1: alice, property2: bob, property3: 42, ...]

如果属性是一个函数,我希望它打印函数的代码,如果它是一个数组,我希望它打印该数组的每个元素。此外,如果该属性是一个对象,它还应该打印它的属性等等...

我已经尝试递归地实现它,但当然调用堆栈很快就变得太大了。然后我转向使用堆栈的迭代实现。这是我得到的:

function getPropertyString(obj) {
var res = "";
var stack = [];
stack.push(obj);
while(stack.length > 0){
var object = stack.pop();
res += "[";
for(var prop in object) {
if(prop == null) continue;
if(typeof object[prop] === 'object') {
stack.push(object[prop]);
} else {
res += prop + ": " +
object[prop].toString().replace(/[\t\r\n]/g, "") + ", ";
}
}
res += "],";
}
return res;
}

如果你有一个像这样的对象,这很好用

var a = {
b : {
c : "hello",
d : "world"
},
e : "alice",
f : "bob",
g : function() {
console.log("hello");
},
h : [1, 2, 3]
}

但假设您修改了 a 以便 a.x = {}; a.x.prototype = a;.然后我的函数就会陷入无限循环。

我该如何解决这个问题?

最佳答案

创建一个已经处理过的对象数组堆栈,并且不要再次处理它们:(我标记了我添加的行来执行此操作)

function getPropertyString(obj) {
var res = "";
var stack = [];
var objectHistory = []; // added this
stack.push(obj);
while(stack.length > 0){
var object = stack.pop();
if (objectHistory.indexOf(object) != -1) continue; // added this
objectHistory.push(object); // added this
res += "[";
for(var prop in object) {
if(prop == null) continue;
if(typeof object[prop] === 'object') {
stack.push(object[prop]);
} else {
res += prop + ": " +
object[prop].toString().replace(/[\t\r\n]/g, "") + ", ";
}
}
res += "],";
}
return res;
}

var a = {
b : {
c : "hello",
d : "world"
},
e : "alice",
f : "bob",
g : function() {
console.log("hello");
},
h : [1, 2, 3]
};

a.x = {
i: "I am X"
};
a.x.prototype = a;

console.log(getPropertyString(a));

关于JavaScript 迭代对象属性 - 陷入循环引用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40111975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com