asp.net-使用intanceof over typeof时出现“太多递归”错误?
作者:互联网
我正在制作一个函数,将对象中的所有日期转换为字符串,当我使用以下函数时,我在FF中出现错误“太多的递归”. (在IE和chrome中也失败)
function datesToString(obj) {
if (obj instanceof Object) {
if (obj instanceof Date) {
obj = "this part does not matter";
} else {
for (var key in obj) { obj[key] = datesToString(obj[key]); }
}
}
return obj;
}
但是当我将其更改为使用typeof时,它工作正常吗?
function datesToString(obj) {
if (obj && typeof obj == "object") {
if (obj instanceof Date) {
obj = "this part does not matter";
} else {
for (var key in obj) { obj[key] = datesToString(obj[key]); }
}
}
return obj;
}
它应该是相同数量的递归.我想念什么吗?为什么第一个示例出现错误,而第二个示例却没有?
更新:
这是我正在使用的对象的示例(以json形式)
Contact = {
"LContactID": "00000000-0000-0000-0000-000000000000",
"CellPhone": "",
"HomePhone": "4564564560",
"OtherPhone": "",
"BirthDate": new Date(-62135575200000),
"SSN": "456456456",
"HowToContact": 1,
"ContactType": 3,
"Address1": "123 test",
"Address2": "apt. 1",
"City": "Valparaiso",
"State": "IN",
"Zip": "46383",
"FullAddress": "123 test, apt. 1",
"BuilderID": "",
"FullAddressWithCityState": "123 test\r\napt. 1\r\nValparaiso, IN 46383",
"WorkHours": "9-5",
"ContactTime": "",
"ContactMethod": "???",
"IsMilitaryOrSelfEmployed": false,
"AlternateContactName": "",
"AlternateContactPhone": "",
"ContactID": "00000000-0000-0000-0000-000000000000",
"Password": null,
"FirstName": "updatetest",
"MiddleName": null,
"LastName": "test_",
"Suffix": null,
"EmailAddress": null,
"EmailAddressAlternate": null,
"WorkPhone": "6546546540",
"WorkPhoneExt": null,
"CreatedOn": new Date(1263597309000),
"CreatedOnOverride": new Date(-62135575200000),
"ModifiedOn": new Date(1264014749000),
"SCRep": "",
"HBCRep": "",
"PPPRep": "",
"DPSRep": "",
"DRSRep": "",
"RDRep": "",
"OwnerID": "00000000-0000-0000-0000-000000000000",
"FullName": "updatetest test_",
"ImportID": 0,
"IncludeEmail": false,
"PreferredLanguage": 1,
"CarbonCopyList": [],
"HearAboutUs": 5,
"HearAboutUsOther": "",
"init": function() { },
"update": function() { },
"load": function() { }
}
看起来,当我删除方法参数(初始化,更新和加载)时,它可以与instanceof示例一起使用.
更新:原来这是一个ASP.Net ScriptManager问题.很抱歉不包括我正在使用ASP.Net网站的事实.ASP.NetScriptManager将函数的方法原型化为Function,当对函数进行递归for in循环时会导致无限循环.
解决方法:
(首先,我说过我在FF 3.5.7上尝试了您的代码,但并没有遇到无限递归.也许您使用了另一个输入示例?)
无论如何,要回答您的问题:
(a)为什么会得到无限递归?因为一个对象可能引用了自己.如果o.f == o,则在o上调用您的函数将触发对o.f的后续调用,该调用实际上是o,依此类推…
(b)为什么两个版本有区别? obj instanceof Object检查obj是Object的实例还是其子类的实例.假定每个Javascript对象都从Object继承,则此条件是微不足道的,因此毫无意义.最终结果是,第一个(如果总是)成功.另一方面,typeof obj ==“ object”检查obj是Object的实例.例如,如果obj是String的实例(在这种情况下,typeof obj会产生String),则这可能是错误的.因此,差异.
标签:scriptmanager,loops,asp-net,javascript,recursion 来源: https://codeday.me/bug/20191106/2001691.html