“太多的递归”在这个用 JavaScript 编写的递归函数中(obj2str)
这段代码有什么问题:
function obj2string(obj) {
var result = '';
for(var i in obj) {
if(typeof(obj[i]) === 'object') {
result += obj2string(obj[i]);
} else {
result += i + " => " + obj[i] + "\n";
}
}
return result;
}
它应该递归地将结果字符串与新属性集中在一起,但是在某些时候递归太多了。
我传递了一个像这样的对象: $(this);
->来自 jQuery。
$(this)
作为此 jQuery 选择器的一个实例: $('.debug');
女巫在当前文档中有一个匹配的类。
What's wront with this piece of code:
function obj2string(obj) {
var result = '';
for(var i in obj) {
if(typeof(obj[i]) === 'object') {
result += obj2string(obj[i]);
} else {
result += i + " => " + obj[i] + "\n";
}
}
return result;
}
It's supposed to recursively concentate the result string with new properties, however there's at somepoint too much recursion.
I was passing an object like this: $(this);
-> from jQuery.
$(this)
Being an instance of this jQuery selector: $('.debug');
witch has one class matched in the current document.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Chrome 控制台中调用 JSON.stringify( jQueryObject ) 会出现“circular_struct”错误。
Calling JSON.stringify( jQueryObject ) in the Chrome console gives a "circular_structure" error.
if(typeof(obj[i]) === 'object') {
将在obj[i]
为null
时执行。你知道吗?尝试使用$.isPlainObject()
(源)if(typeof(obj[i]) === 'object') {
will execute ifobj[i]
isnull
. Are you aware of that? Try it with$.isPlainObject()
(source)几乎可以肯定,您有一个循环引用(即输入对象的属性之一(或这些属性的属性之一,等等))引用结构中的另一个属性,该属性返回到自身。
想一想就会明白为什么这行不通。
You almost certainly have a circular reference (i.e. one of the properties of the input object (or one of those property's properties, and so on)) references another property in the structure that leads back to itself.
A moment's thought should reveal why this can't possibly work.