区分 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 (将#修改为@)