在这个递归函数中,我想替换(嵌套)对象中的值。
var testobj = {
'user': {
'name': 'Mario',
'password': 'itseme'
}
};
updateObject('emesti', 'password', testobj)
function updateObject(_value, _property, _object) {
for(var property in _object) {
if(property == _property) {
_object[property] = _value;
}
else if(objectSize(_object) > 0) {
updateObject(_value, _property, _object[property]);
}
}
return _object
};
function objectSize(_object) {
var size = 0, key;
for (key in _object) {
if (_object.hasOwnProperty(key)) size++;
}
return size;
};
运行后,firefox 在 else if(objectSize(_object) > 0) {
行抛出异常“太多递归”。
编辑: 如果我设置
function updateObject(_value, _property, _object) {
for(var property in _object) {
if(property == _property) {
_object[property] = _value;
}
else if(_object[property].hasOwnProperty(_property)) {
updateObject(_value, _property, _object[property]);
}
}
return _object
};
它有效,但它只搜索一级。如果我在嵌套对象中有一个嵌套对象,它就不会工作。
还有什么想法吗?
编辑: 此问题出现在 Firefox 3.6 中。它适用于 Chrome。
最佳答案
我不是 100% 熟悉如何用 Javascript 做事,但本质上你想要这样的东西:
var testobj = {
'user': {
'name': 'Mario',
'password': 'itseme',
'bleh': {
'password': 'something'
}
}
};
function updateObject(_value, _property, _object) {
for(var property in _object) {
if(property == _property) {
_object[property] = _value;
}
else if(explorable(_object[property])) {
updateObject(_value, _property, _object[property]);
}
}
return _object
};
function explorable(_object) {
return typeof(_object) != "string";
};
updateObject('emesti', 'password', testobj);
document.writeln(testobj.user.password); // "emesti"
document.writeln(testobj.user.bleh.password); // "emesti"
目前,任何不是字符串的东西都是可探索的
。这可能适用于所有情况,也可能不适用于所有情况,因此您可能希望更好地定义什么是可探索
。
另请注意,递归现在会更新所有 匹配的属性。
关于javascript - 太多的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2935728/