如何解决区分 HTML 元素和 JSON 对象
我已经意识到 typeof {}
(JSON 对象)和 typeof document.getElementById("foo")
(HTML 元素)都等于“对象”
在这种特定情况下,我不能使用 .toString()
并与例如 includes()
进行比较。
我一直无法找到任何其他替代方案。我认为在(JSON 或 HTML)对象中检查未定义的 innerHTML 可能会起作用,但显然,如果 JSON 对象有一个叫做那个的键,它就不会起作用。
如何区分两者?谢谢!
编辑:
function parseJSON(object) {
if (typeof object !== "object") {
object = JSON.parse(object);
}
for (let [key,value] of Object.entries(object)) {
if (typeof value == "object") {
object[key] = parseJSON(value);
}
try {
var val = eval(value);
if (val.toString() == ... || typeof val == ...) { //Comparison is here
val = value;
}
console.log(val,value);
} catch (error) {
switch (error.constructor) {
case SyntaxError:
continue;
case ReferenceError:
object[key] = value;
continue;
default:
console.log(new Error().stack);
continue;
}
}
object[key] = val;
}
return object;
}
编辑 2 (JSON):
{
"CSS_ATKINSON_FONT": "chrome.runtime.getURL('ttaddons/fonts/Atkinson.css')",//this is supposed to be converted to an URL and it will.
"REQUESTS": {
"mazeTheme": "mazeTheme" //this becomes an element through eval()
},"THEMES": [
{
"theme": "light","gameTheme": "g_url('assets/images/game/game')" //this function does not exist in the window and the string should remain as is. It's why I have the referenceError check in place
},{
"theme": "dark","gameTheme": "d_url('ttaddons/game/darkGame')" //neither this
}
],"MUSIC": {
"Russianmarch": "Russianmarch"
},"POPUP": {
"ELEMENTS": {
"darkTheme": "#darkTheme" //this is not supposed to become an element,and does not either.
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。